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

Pan*_*kaj 6 mongoose mongodb

我在帖子模型中嵌入了评论.我正在使用mongoosejs.在帖子中推送新评论后,我想访问新添加的嵌入评论的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);
   })


});
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,不返回注释的id.请注意,在db中创建了一个_id字段.

架构看起来像

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

var PostSchema = new Schema({
    ...
    comments:[CommentSchema],
    ...
});
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 8

文档的_id值实际上是由客户端分配的,而不是服务器.因此,_id您可以在致电后立即获取新评论:

post.comments.push(comment);
Run Code Online (Sandbox Code Playgroud)

嵌入文档推向post.comments都会有_id指定的,因为它的加入,所以你可以从那里把它:

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

  • 尽管已将其标记为已解决,但是如果使用$ push在数组中添加文档该怎么办。在这种情况下,如何获取ID。例如:`let newValue = await model.findOneAndUpdate({name:'NEW Value','comments.name':{$ ne:newComment.name}},{$ push:{comments:newComment}},{new:true } .exec();` (2认同)

Gle*_*enn 5

您可以手动生成 _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
Run Code Online (Sandbox Code Playgroud)