Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb,获取新推送的嵌入对象的id_Mongodb_Mongoose - Fatal编程技术网

Mongodb,获取新推送的嵌入对象的id

Mongodb,获取新推送的嵌入对象的id,mongodb,mongoose,Mongodb,Mongoose,我在posts模型中嵌入了注释。我用的是猫鼬。在文章中推送新评论后,我想访问新添加的嵌入评论的id。不知道怎么弄到 下面是代码的样子 var post = Post.findById(postId,function(err,post){ if(err){console.log(err);self.res.send(500,err)} post.comments.push(comment); post.save(function(err,story){ if(

我在posts模型中嵌入了注释。我用的是猫鼬。在文章中推送新评论后,我想访问新添加的嵌入评论的id。不知道怎么弄到

下面是代码的样子

var post = Post.findById(postId,function(err,post){

   if(err){console.log(err);self.res.send(500,err)}

   post.comments.push(comment);

   post.save(function(err,story){
       if(err){console.log(err);self.res.send(500,err)}
           self.res.send(comment);
   })


});
在上面的代码中,不会返回注释的id。注意,数据库中创建了一个_id字段

该模式看起来像

var CommentSchema = new Schema({
  ...
})

var PostSchema = new Schema({
    ...
    comments:[CommentSchema],
    ...
});

文档的
\u id
值实际上是由客户端而不是服务器分配的。因此,新注释的
\u id
在您调用以下命令后立即可用:

post.comments.push(comment);
推送到
post.comments
的嵌入文档将在添加时分配其
\u id
,因此您可以从那里提取它:

console.log('_id assigned is: %s', post.comments[post.comments.length-1]._id);

\u id
字段在客户端生成,您可以通过
comment.id

样品

 > var CommentSchema = new Schema({
     text:{type:String}
  })

 > var CommentSchema = new mongoose.Schema({
     text:{type:String}
 })

 > var Story = db.model('story',StorySchema)
 > var Comment = db.model('comment',CommentSchema)
 > s= new Story({title:1111})
   { title: '1111', _id: 5093c6523f0446990e000003, comments: [] }
 > c= new Comment({text:'hi'})
   { text: 'hi', _id: 5093c65e3f0446990e000004 }
 > s.comments.push(c)
 > s.save()
在mongo db shell中验证

    > db.stories.findOne()
{
    "title" : "1111",
    "_id" : ObjectId("5093c6523f0446990e000003"),
    "comments" : [
        {
            "_id" : ObjectId("5093c65e3f0446990e000004"),
            "text" : "hi"
        }
    ],
    "__v" : 0
}

您可以手动生成_id,这样就不必担心以后会把它拉回来

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

// then set the _id key manually in your object

_id: myId

// or

myObject[_id] = myId

// then you can use it wherever

comment
从何而来?它是一个json对象,在给定的代码之上的另一部分代码中创建。虽然它已被标记为已解决,但如果使用$push将文档添加到数组中该怎么办。在这种情况下如何获取id。示例:
let newValue=wait model.findOneAndUpdate({name:'NEW Value',comments.name':{$ne:newComment.name},{$push:{comments:newComment},{NEW:true}).exec()