Mongodb无法按ID查询子文档(返回null) [英] Mongodb Can't Query SubDocument by ID (returns null)

查看:450
本文介绍了Mongodb无法按ID查询子文档(返回null)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个猫鼬模式:

So I have this Mongoose Schema:

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的comment数组中查询Comment.

And I'm trying to query a Comment inside the comment array in post.

这是我正在尝试的端点:

This is the endpoint I'm trying:

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'})
  })
})

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

However, this gives the following terminal output:

value of req.body:  { id: '5c9bd902bda8d371d5c808dc' }
the value of the found doc:  null

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

That's not correct...I've verified the ID is correct - why is the comment doc not being found?

我已经尝试过此解决方案(找不到正在搜索的文档通过使用Mongoose使用ObjectId )来设置对象ID,如下所示:

I've attempted this solution (Can't find documents searching by ObjectId using Mongoose) by setting the objectID like this:

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' }
value of objid req id :  5c9bd902bda8d371d5c808dc
the value of the found doc:  []

因此,尽管它似乎比我的解决方案要好,但这还不是解决方案.

So, this is not yet a solution although it appears to be better than what I had.

推荐答案

无论您认为多少,都不会查询ObjectId.您正在查询编码为十六进制字符串的ObjectId,这是同一件事.正确地进行类型转换,您可能会获得更大的成功.

You aren't querying for an ObjectId, no matter how much you think you are. You are querying for the ObjectId encoded as a hexidecial string, which is not the same thing. Properly typecast and you will likely have far more success.

编辑后,从mongo(JS)REPL shell进行了详细阐述:

Edited to elaborate, from a 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)上的此处搜索猫鼬类型转换ObjectId"(不带引号;或者只是猫鼬ObjectId"…),您会发现很多答案,因为这对猫鼬用户来说是一个特别常见的问题.

After our IRC discussion, there seems to be difficulty in understanding the "searchable terms" in the answers you are being given. Search here on StackOverflow (or Google, or DDG) for "mongoose typecast ObjectId" (without quotes; or just "mongoose ObjectId"…) and you will find many answers, as this is a particularly common problem for Mongoose users.

这篇关于Mongodb无法按ID查询子文档(返回null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆