【问题标题】:Mongodb, getting the id of the newly pushed embedded objectMongodb,获取新推送的嵌入对象的id
【发布时间】:2017-10-30 00:27:51
【问题描述】:

我在帖子模型中嵌入了 cmets。我正在使用猫鼬。在帖子中推送新评论后,我想访问新添加的嵌入式评论的 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。请注意,在 db 中创建了一个 _id 字段。

架构看起来像

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

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

【问题讨论】:

  • comment 来自哪里?
  • 它是一个 json 对象,它是在代码的另一部分中创建的......在给定的上面。

标签: mongodb mongoose


【解决方案1】:

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

post.comments.push(comment);

推送到post.comments 的嵌入式文档将在添加时分配其_id,因此您可以从那里提取它:

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

【讨论】:

  • 虽然已经标记为已解决,但是如果使用 $push 将文档添加到数组中怎么办。在这种情况下如何获取 id。示例:let newValue = await model.findOneAndUpdate( { name: 'NEW Value', 'comments.name': {$ne: newComment.name} }, { $push: {comments: newComment} }, { new: true } ).exec();
【解决方案2】:

您可以手动生成_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

【讨论】:

    【解决方案3】:

    _id字段在客户端生成,可以通过comment.id获取嵌入文档的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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      相关资源
      最近更新 更多