简体   繁体   English

保存后访问子文档 ID - mongoose

[英]Accessing a sub-document ID after save - mongoose

When a user is created on my app their details are saved on the MongoDB using mongoose.在我的应用程序上创建用户时,他们的详细信息将使用 mongoose 保存在 MongoDB 上。 The user schema contains sub-documents and I am trying to access the _id if the sub-document after using the user.save function. user schema包含子文档,如果使用user.save函数后子文档,我试图访问_id

The schema is below:架构如下:

{
  name: String,
  email: String,
  address: String,
  phone:[
     {landLine: Number,
      mobile: Number}
   ]
}

I can access the name, email and address easily like so:我可以像这样轻松访问姓名、电子邮件和地址:

console.log(user.name + user.email + user.address)

I tried user.phone._id but it returns undefined .我试过user.phone._id但它返回undefined I think because phone is an array of objects.我认为因为phone是一个对象数组。

 user.save(function(err) {
                if (err)
                    throw err;
                else {
                    console.log("user ID " + user._id); // SUCCESS!!
                    console.log("user sub-document ID " + user.phone._id); // UNDEFINED!!
                    return (null, user);
                }
            });

How can I access the _id of the sub-document inside the save function right after the user is created and saved into mongoDB?如何在创建用户并保存到 mongoDB 后立即访问save函数中子文档的 _id?

There are a couple of approaches to getting this information, but personally I prefer the "atomic" modification method using$push .有几种方法可以获取此信息,但我个人更喜欢使用$push的“原子”修改方法。

The actual implementation here is helped by mongoose automatically including an ObjectId value which is "monotonic" and therefore always increasing in value.这里的实际实现由 mongoose 自动包含一个ObjectId值帮助,该值是“单调的”,因此值总是增加。 So this means that my method for handling this even works with a $sort modifier applied to the$push .所以这意味着我的处理方法甚至适用于应用于$push$sort修饰符。

For example:例如:

// Array of objects to add
var newNumbers = [
  { "landline": 55555555, "mobile": 999999999 },
  { "landline": 44455555, "mobile": 888888888 }
];

User.findOneAndUpdate(
  { "email": email },
  { "$push": { "phone": { "$each": newNumbers } } },
  { "new": true },
  function(err,user) {
    // The trick is to sort() on `_id` and just get the
    // last added equal to the length of the input
    var lastIds = user.phone.concat().sort(function(a,b) {
      return a._id > b._id
    }).slice(-newnumbers.length);
  }
)  

And even if you used a $sort modifier:即使您使用了$sort修饰符:

User.findOneAndUpdate(
  { "email": email },
  { "$push": { "phone": { "$each": newNumbers, "$sort": { "landline": 1 }  } } },
  { "new": true },
  function(err,user) {
    var lastIds = user.phone.concat().sort(function(a,b) {
      return a._id > b._id
    }).slice(-newnumbers.length);
  }
)  

That little trick of "sorting" a temporary copy on the _id value means that the "newest" items are always at the end._id值上“排序”临时副本的小技巧意味着“最新”项目总是在最后。 And you just need to take as many off the end as you added in the update.而且您只需要在更新中添加尽可能多的内容即可。

The arguable point here is that it's actually mongoose that is inserting the _id values in the first place.这里有争议的一点是,实际上是mongoose首先插入了_id值。 So in fact those are being submitted in the request made to the server for each array item.所以实际上这些是在为每个数组项向服务器发出的请求中提交的。

You "could" get fancy and use "hooks" to record those ObjectId values that were actually added to the new array members in the update statement.您“可以”花哨并使用“钩子”来记录那些实际添加到更新语句中的新数组成员的ObjectId值。 But it's really just a simple process of returning the last n "greatest" _id values from the array items anyway, so the more complex approach is not needed.但这实际上只是从数组项中返回最后n “最大” _id值的简单过程,因此不需要更复杂的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM