Mongodb无法按ID查询子文档(返回null)

所以我有这个猫鼬架构:


var mongoose = require('mongoose');

var Schema = mongoose.Schema;


var CommentSchema = new Schema({

  body: {type: String, required: true, max: 2000},

  created: { type: Date, default: Date.now },

  flags: {type: Number, default: 0},

  lastFlag: {type: Date, default: Date.now()},

  imageBanned: {type: Boolean, default: false},

  fileName: {type: String, default: ""}

}, {

  writeConcern: {

    w: 0,

    j: false,

    wtimeout: 200

  }  

});


var PostSchema = new Schema({

  body: {type: String, required: true, max: 2000},

  created: { type: Date, default: Date.now },

  flags: {type: Number, default: 0},

  lastFlag: {type: Date, default: Date.now()},

  fileName: {type: String, default: ""},

  imageBanned: {type: Boolean, default: false},

  board: {type: String, default: ""},

  comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]

}, {

  writeConcern: {

    w: 0,

    j: false,

    wtimeout: 200

  }  

});



var Post =  mongoose.model('Post', PostSchema);

var Comment = mongoose.model('Comment', CommentSchema)


module.exports = {Post, Comment}

我正在尝试在帖子的评论数组中查询评论。


这是我正在尝试的端点:


router.post('/flagComment', (req, res, next)=>{

  console.log('inside /flagComment')

  console.log('value of req.body: ', req.body)

  model.Post.findOne({"comments._id": req.body.id}).exec((err, doc)=>{

    if(err){

      console.log('there was an error: ', err)

    }

    console.log('the value of the found doc: ', doc)

    res.json({dummy: 'dummy'})

  })

})

但是,这提供了以下终端输出:


value of req.body:  { id: '5c9bd902bda8d371d5c808dc' }

the value of the found doc:  null

那是不正确的...我已经验证了ID是正确的-为什么找不到注释文档?


慕村9548890
浏览 480回答 3
3回答

POPMUISE

尝试先检查参考数据,然后再查询注释的_id。*除了评论ID外,还可以从前端获取帖子ID,这样会更容易。Post.findOne({_id:'postId'}).populate({  path  : 'comment',  match : { _id : 'commentId' }}).exec(...);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript