为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕村9548890 2021-03-29 17:15:30
所以我有这个猫鼬架构: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是正确的-为什么找不到注释文档?
查看完整描述

3 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

尝试先检查参考数据,然后再查询注释的_id。


*除了评论ID外,还可以从前端获取帖子ID,这样会更容易。


Post.findOne({_id:'postId'})

.populate({

  path  : 'comment',

  match : { _id : 'commentId' }

})

.exec(...);


查看完整回答
反对 回复 2021-04-08
  • 3 回答
  • 0 关注
  • 479 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信