node.js - 查找插入 mongoose 的最新子文档的 id

标签 node.js mongodb mongoose

我有一个模型架构:

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。

最佳答案

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

因此,您还应该注意,即使您有一个子文档 _id - 在您保存它之前它还不存在于 Mongo 中,因此请注意您可能采取的任何 DOCRef 操作。

关于node.js - 查找插入 mongoose 的最新子文档的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18760087/

相关文章:

node.js - 在 Node js 应用程序中导入 Mongoose 架构无法正常工作

mongodb - 限制嵌入文档的大小

linux - Nginx 上的 Scalatra : how to set up?

javascript - 如何根据游戏应用程序的聚合管道中的总点数计算排名

node.js - 什么是 node.js 中的 require ("http")

javascript - 在 Node 模块中使用 async - 如何返回结果?

mongodb - 使 $elemMatch (projection) 返回所有符合条件的对象

javascript - 如何删除 Mongoose 中的特定子文档

Javascript/我的动态函数安全吗?

node.js - TypeError : firestoreService. snapshot_ 不是函数