Javascript Mongodb可以';按ID查询子文档(返回null)

Javascript Mongodb可以';按ID查询子文档(返回null),javascript,node.js,database,mongodb,mongoose,Javascript,Node.js,Database,Mongodb,Mongoose,所以我有一个猫鼬模式: 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}, la

所以我有一个猫鼬模式:

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}
我试图在post中的注释数组中查询注释

这是我正在尝试的端点:

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
value of req.body:  { id: '5c9bd902bda8d371d5c808dc' }
value of objid req id :  5c9bd902bda8d371d5c808dc
the value of the found doc:  []
这是不正确的…我已经验证了ID是正确的-为什么找不到注释文档

编辑:

我尝试通过如下方式设置objectID来实现此解决方案()

var ObjectId = require('mongoose').Types.ObjectId; 

router.post('/flagComment', (req, res, next)=>{
  console.log('inside /flagComment')
  console.log('value of req.body: ', req.body)
  console.log('value of objid req id : ',  ObjectId(req.body.id))
  model.Post.find({"comments._id": ObjectId(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
value of req.body:  { id: '5c9bd902bda8d371d5c808dc' }
value of objid req id :  5c9bd902bda8d371d5c808dc
the value of the found doc:  []

因此,这还不是一个解决方案,尽管它看起来比我的要好。

无论您认为自己是多么的强大,您都不会查询ObjectId。您正在查询编码为十六进制字符串的ObjectId,该字符串不是同一事物。正确的打字,你可能会有更多的成功

根据mongo(JS)REPL shell进行了详细编辑:

> // Omitting the _id, or generating a new one, are equivalent during insert.
> db.foo.insert({_id: ObjectId()})
WriteResult({ "nInserted" : 1 })

> db.foo.find()  // As expected, we get back our _real_ ObjectId value.
{ "_id" : ObjectId("5c9cfab873724727778c0730") }

> // Can we "insert the record again" using a string version of the ID?
> db.foo.insert({_id: "5c9cfab873724727778c0730"})
WriteResult({ "nInserted" : 1 })  // Sure as heck can! No unique violation!

> db.foo.find()  // Because THESE ARE NOT THE SAME
{ "_id" : ObjectId("5c9cfab873724727778c0730") }
{ "_id" : "5c9cfab873724727778c0730" }

在我们的IRC讨论之后,似乎很难理解给出的答案中的“可搜索术语”。在StackOverflow(或Google,或DDG)上搜索“mongoose typecast ObjectId”(不带引号;或仅搜索“mongoose ObjectId”…),您将找到许多答案,因为这是mongoose用户特别常见的问题。

一次尝试先填充参考数据,然后查询注释的id

*除了注释id之外,还可以从前端获取帖子id,这样会更容易

Post.findOne({_id:'postId'})
.populate({
  path  : 'comment',
  match : { _id : 'commentId' }
})
.exec(...);

你能提供一个代码示例吗?我不确定我是否理解。@Peterwey和我不猫鼬,也不JS。答案很清楚:在尝试使用值进行查询之前,将值键入real
ObjectId
。十六进制编码的字符串!=二进制值,与base64编码字符串相同!=原始二进制值。好的,谢谢你的帮助,但是这个答案还不足以让我找到解决方案。谢谢你。@PeterWeyand笑了,我用了一个
mongo
REPL shell中的一些代码进行了更新,它是JS。此代码从使用
\u id
上的唯一索引来证明比较的不同性和无能力/不适当性的角度演示了您遇到的确切问题。给出的答案(“正确的”)站得住脚。谢谢……我的意思是这是可行的,但是……感觉有点像后门黑客。为什么我不能直接按id查询评论?我认为这样做需要A)obv。传递另一个id和B)我认为在我不需要的时候搜索帖子,这是另一个查询。如果你检查数据库,mongodb不会像你搜索“评论”一样将数据保存在评论字段中。_id,它会以类似{“$ref”:“评论”的格式保存,“$id”:ObjectId(“commentid”),“$db”:“dbname”}我不相信这是正确的。这是一篇文章的终端输出:
{flags:0,lastFlag:2019-03-27T21:00:54.316Z,fileName:'1553720454192&&hotdog.png',imagebanked:false,board:'nsfw',comments:[{flags:0,lastFlag:2019-03-27T21:01:03.540Z,imagebanked:false,文件名:'1553720463408&&hotdog.png',正文:'dadf',created:2019-03-27T21:01:03.540Z,'uuuu v:0}],正文:'dog',created:2019-03-27T21:11:15.575Z,'uu v:0}
如果您的问题已得到回答,请确保接受答案以供进一步参考。答案尚未回答-请参阅我的评论,谢谢。可能重复…或-虽然这些问题与问题的数据存储方面有关,但每个问题都有解决方案。