【问题标题】:Mongoose : Update a nested object in an arrayMongoose:更新数组中的嵌套对象
【发布时间】:2019-07-19 15:46:07
【问题描述】:

我的项目中有这个猫鼬模式:

const mongoose = require('mongoose');
const schema = mongoose.Schema;

var WebsiteModel = new schema({

    name: {
        type: String,
        required: true,
        unique: true,
        lowercase: true
    },

    createdOn: {
        type: String,
        required: true,
        default: Date.now
    },

    country: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Countries',
        required: true
    },

    categories: [{

        category: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Categories'
        },

        name: {
            type: String,
            required: true,
            lowercase: true,
        },

        path: {
            type: String,
            required: true
        },

        enabled: {
            type: Boolean,
            required: true,
            default: false
        },

        description: {
            type: String,
            required: true,
            default: false
        },
    }]
});

module.exports = mongoose.model('Websites', WebsiteModel);

我想确保当我在类别数组中更新或添加文档时,名称、路径和类别 ID 必须是唯一的。所以这是我尝试过的:

editWebsiteCategory = (req, resp) => {
    var websiteId = req.params.websiteid;
    var categoryId = req.params.categoryid;
    var categoryDatas = { ...req.body };
    var condition = {
        _id: websiteId,
        'categories.name':{$ne:{categoryDatas.name}},
        'categories.path':{$ne:{categoryDatas.path}},
        'categories._id':{$ne:{categoryDatas._id}},
        'categories._id': categoryId
    };
    if (categoryId && websiteId) {
        websiteModel.findOneAndUpdate(condition,
            { $set: { 'categories.$': categoryDatas } },
            (err, result) => {
                if (err) {

                    resp.status(500).json({ msg: "Internal Server Error !" });
                }

                if (result) {
                    resp.status(200).json(result);
                }
            })
    }
    else {
        resp.status(500).json({ msg: "Internal Server Error !" });
    }
}

CategoryDatas 是一个对象,其中包含保存类别所需的所有属性。它的结构类似于上面 WebsiteModel 中的 categories 数组中的对象文档。

当我运行 editWebsiteCategory 方法时,即使指定的名称和路径对应于另一个现有类别,数据也会保存在数据库中,并且不会返回错误。所以最后我有两个或更多具有相同名称和路径的类别。这正是我不想要的。

有人可以帮忙吗?谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在 mongo 风格中,使用 '$' 位置运算符。详情请查看link

    db.my_collection.update(
      {_id: ObjectId(document_id), my_array.1 : 1 },
      { $set: { "my_array.$.content" : "NEW content B" } }
    )
    

    【讨论】:

    • 谢谢,但没用。我仍然有许多具有相同名称和路径的类别
    • 可以分享一下表格的模型结构吗? @THEHOLYSPIRIT
    • 请用女巫桌。 WebsiteModel 在帖子中指定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多