【问题标题】:node js returns undefined from mongodb obejct inner value节点js从mongodb obejct内部值返回未定义
【发布时间】:2017-01-29 10:42:21
【问题描述】:

我有一个从 mongodb 检索到的存储对象, 我有兴趣使用值 store.cmets。

我记录了商店的价值,它是:

store:{ _id: 57e246f73e63d635cce3d174,
  __v: 0,
  comments: 57e246f73e63d635cce3d177,
  loc: [ 105.832321, 105.233272 ],
  name: '24 store',
  reportedFalse: [],
  products: [],
  currentRanking: 
   { likes: 57e246f73e63d635cce3d175,
     dislikes: 57e246f73e63d635cce3d176 },
  timePosted: Wed Sep 21 2016 11:38:15 GMT+0300 (Jerusalem Summer Time) },

然后我记录了对象 cmets 值的值 - result.cmets

store comments objectid: undefined

当我稍后尝试按 cmets 值搜索时,似乎无法成功搜索。因为搜索返回null,虽然我看到在我的数据库中我在“cmets”表/模式中有一个具有相同ID的对应对象....

Comments.findById(commentsId,function(commentsErr,commentsArrObj){
...
cb(null, commentsArrObj._id);
                    }

我明白了:

TypeError: Cannot read property '_id' of null

这是我的架构的一部分供参考:

        name: String,
        comments: mongoose.Schema.Types.ObjectId, // each comment has a object id - responder, link curl? crud?  to his profile, profile pic, date time.
        timePosted : { type: Date, default: Date.now },
        currentRanking: {
            likes: mongoose.Schema.Types.ObjectId, // a votes document
            dislikes: mongoose.Schema.Types.ObjectId // a votes document
        },

【问题讨论】:

  • commentsObjectId,所以无法访问comments._id
  • 嗨,谢谢。第二个查询相当愚蠢,我实际上搜索了一个对象并返回它的_id,它应该仍然有效......我认为问题在于我提到的第一件事,我无法访问 result.cmets

标签: javascript node.js mongodb syntax mongoose


【解决方案1】:

在你的架构中你必须使用'ref'

comments: mongoose.Schema.Types.ObjectId,ref:'comments'(modal name of comments)

引用 cmets 架构并使用填充 cmets 来获取 cmets 数据。

【讨论】:

  • 谢谢,我试试。一旦我有了 ref,我可以在什么查询中访问实际对象?假设 store.cmets 持有 ref... 非常感谢。我也读过它。
【解决方案2】:

控制台错误对象“cmetsErr”,然后检查它正在打印什么。如果您的 cmetsId 类型更改为字符串,则可能是不从架构中找到 cmets 的可能原因。尝试将其转换为 ObjectId。

使用:

Comments.findById(new mongoose.Types.ObjectId(id),function(commentsErr,commentsArrObj){
          cb(null, commentsArrObj._id);
})

建议:使用 mongoose 使用 ref 填充记录,这样您就不需要单独查找查询来获取 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2020-07-14
    相关资源
    最近更新 更多