【问题标题】:Mongoose how to auto add _id to objects in array within collection item?Mongoose如何自动将_id添加到集合项中数组中的对象?
【发布时间】:2022-02-08 23:50:12
【问题描述】:

我有一个如下所示的 mongo 集合:

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

我正在使用findByIdAndUpdate(带有猫鼬)将一个项目添加到项目数组中:

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);
        }
    }
);

这很好用,但它不会为插入到items 数组中的每个对象添加_id。我真的需要每个人都有一个 id。

我猜它来自使用的方法findByIdAndUpdate,因为它看起来更像是更新而不是插入。如果我的想法是正确的。

使用 mongodb 3.2.10 和 mongoose 4.7.6。

任何帮助将不胜感激。 谢谢。

编辑:_id: (auto set) 不是真实的,它是通过 mongo 自动添加的。但仅限于顶级对象。

【问题讨论】:

  • 如果将setDefaultsOnInsert 选项设置为true 会发生什么?

标签: node.js mongodb mongoose


【解决方案1】:

在这个帖子中找到了解决方案:mongoDB : Creating An ObjectId For Each New Child Added To The Array Field

基本上,添加了

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

然后强制创建:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我的想法,但是,当我通过 mongo shell 检查时,我没有看到任何 _id 被添加。仅针对我编写_id: (auto set) 的顶级对象。
    • 另一种方法 _id: {type:ObjectIdSchema, default: function () { return new ObjectId()} }
    • 签入其他一些 GUI,例如 RoboMongo。文档中应该有一个唯一的 id,它可以是 Auto Generated ObjectId with key '_id'
    • 是的,我已经检查过 robomongo 并且确实没有。检查此屏幕截图:s27.postimg.org/iw7zftr6b/… 我会尝试您的第二条评论。
    • ObjectId('587cd...') 是您的文档生成的唯一 ID
    【解决方案3】:

    如果您没有在 Schema 中定义 _id,mongoose 会自动将 _id 添加到数组项中。 例如:

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

    现在当你插入一行时,结果是这样的:

    {name : 'Iran', 城市 : [{_id : 6202902b45f0d858ac141537,name : '大不里士'}]}

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2019-02-13
      • 1970-01-01
      • 2013-08-15
      • 2020-10-27
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2018-08-15
      相关资源
      最近更新 更多