查找插入 mongoose 的最新子文档的 id [英] find id of latest subdocument inserted in mongoose

查看:30
本文介绍了查找插入 mongoose 的最新子文档的 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型架构:

var A = new Schema ({
  a: String,
  b : [ { ba: Integer, bb: String } ]
}, { collection: 'a' } );

然后

    var M = mongoose.model("a", A);
    var saveid = null;
    var m = new M({a:"Hello"});
    m.save(function(err,model){
       saveid = model.id;
   });  // say m get the id as "1"

然后

    m['b'].push({ba:235,bb:"World"});
    m.save(function(err,model){
      console.log(model.id); //this will print 1, that is the id of the main Document only. 
//here i want to find the id of the subdocument i have just created by push
    });

所以我的问题是如何找到刚刚推入模型的一个字段中的子文档的 id.

So my question is how to find the id of the subdocument just pushed in one field of the model.

推荐答案

我也一直在寻找这个答案,但我不确定我是否喜欢访问数组的最后一个文档.但是,我确实有一个替代解决方案.方法 m['b'].push 将返回一个整数,1 或 0 - 我假设这是基于推送的成功(在验证方面).但是,为了访问子文档,尤其是子文档的 _id - 您应该先使用 create 方法,然后使用 push 方法.

I've been looking for this answer as well, and I'm not sure that I like accessing the last document of the array. I do have an alternative solution, however. The method m['b'].push will return an integer, 1 or 0 - I'm assuming that is based off the success of the push (in terms of validation). However, in order to get access to the subdocument, and particularly the _id of the subdocument - you should use the create method first, then push.

代码如下:

var subdoc = m['b'].create({ ba: 234, bb: "World" });
m['b'].push(subdoc);
console.log(subdoc._id);
m.save(function(err, model) { console.log(arguments); });

发生的事情是,当您将对象传递给 push 或 create 方法时,Schema 转换会立即发生(包括验证和类型转换之类的事情)——这意味着这是创建 ObjectId 的时间;不是当模型被保存回 Mongo 时.事实上,mongo 不会自动为子文档分配 _id 值,这是 mongoose 的特性.Mongoose create 记录在此处:create docs

What is happening is that when you pass in the object to either the push or the create method, the Schema cast occurs immediately (including things like validation and type casting) - this means that this is the time that the ObjectId is created; not when the model is saved back to Mongo. In fact, mongo does not automatically assign _id values to subdocuments this is a mongoose feature. Mongoose create is documented here: create docs

因此,您还应该注意,即使您有一个子文档 _id - 在您保存它之前它还没有出现在 Mongo 中,所以不要担心您可能采取的任何 DOCRef 操作.

You should also note therefore, that even though you have a subdocument _id - it is not yet in Mongo until you save it, so be weary of any DOCRef action that you might take.

这篇关于查找插入 mongoose 的最新子文档的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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