亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 515 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號