简体   繁体   English

Mongoose 如何将_id 自动添加到集合项中数组中的对象?

[英]Mongoose how to auto add _id to objects in array within collection item?

i have a mongo collection that looks like this:我有一个看起来像这样的 mongo 集合:

{
    name: string
    _id: (auto set)
    items: array[
        name: string
        url: string
        items: array[
            {
                name: string,
                url: string,
                items: []
            }
        ]
    ]
}

I'm using findByIdAndUpdate (with mongoose) to add an item into the items array:我正在使用findByIdAndUpdate (使用 mongoose)将一个项目添加到项目数组中:

Menu.findByIdAndUpdate(
    req.body.parentid, 
    {
        $push: {
            items: {
                name: req.body.item.name, 
                url: req.body.item.url,
                items: []
            }
        }
    },
    {
        safe: true, 
        upsert: true, 
        new: true
    },
    function(err, model) {
        if (err !== null) {
            console.log(err);
        }
    }
);

This works fine, but it does not add an _id to each object inserted into the items array.这工作正常,但它不会为每个插入items数组的 object 添加一个_id And i really need an id for each one.我真的需要每个人的身份证。

I'm guessing it comes from the method used, findByIdAndUpdate as it looks more like an update rather than an insert.我猜它来自使用的方法findByIdAndUpdate ,因为它看起来更像是更新而不是插入。 If my thinking is correct.如果我的想法是正确的。

Using mongodb 3.2.10 and mongoose 4.7.6.使用 mongodb 3.2.10 和 mongoose 4.7.6。

Any help would be really appreciated.任何帮助将非常感激。 Thanks.谢谢。

EDIT: the _id: (auto set) is not real, it's being automatically added via mongo.编辑: _id: (auto set)不是真实的,它是通过 mongo 自动添加的。 But just at the top level objects.但只是在顶层对象。

Found the solution in this thread: mongoDB : Creating An ObjectId For Each New Child Added To The Array Field 在这个帖子中找到了解决方案: mongoDB:为每个添加到数组字段的新子项创建一个ObjectId

basically, added 基本上,补充说

var ObjectID = require('mongodb').ObjectID;

and then forcing the creation: 然后强制创建:

$push: {
    items: {
        _id: new ObjectID(),
        name: req.body.item.name, 
        url: req.body.item.url,
        items: []
    }
}

你不需要在mongoose架构中sepcify _id :(自动设置)它会自动为每个文档添加唯一的_id。

if you don't define _id in Schema, mongoose automatically add a _id to array item.如果您没有在 Schema 中定义 _id,mongoose 会自动向数组项添加一个 _id。 for example:例如:

const countrySchema = new Schema({
  name: {
    type: String
  },
  cities: [
    {
      // don't define _id here.
      name: String
    }
  ],
});

now when you insert a row, the result is something like this:现在当你插入一行时,结果是这样的:

{name: 'Iran', cities: [{_id: 6202902b45f0d858ac141537,name: 'Tabriz'}]} {名称:'伊朗',城市:[{_id:6202902b45f0d858ac141537,名称:'大不里士'}]}

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

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