【问题标题】:Mongoose edit an object in an array or add it to the array if it doesn't exist by a certain propertyMongoose 编辑数组中的对象,如果某个属性不存在,则将其添加到数组中
【发布时间】:2016-05-03 00:42:39
【问题描述】:

我有一个如下所示的架构:

var RoomSchema = new mongoose.Schema({
    venueId: { type: mongoose.Schema.ObjectId, ref: 'User' },
    name: {
        type: String
    },
    special: [{
            date: {type: Date},
            pricing: {
                isOpen: { type: Boolean },
                openTime: { type: String }
            }
        }]
});

并且我想将一个新对象推送到“特殊”数组中,除非数组中已经存在“日期”。我知道如果它不存在 upsert 会添加一个新对象,但是如果该对象仅通过 date 属性而不是整个对象存在,我该如何搜索?

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    假设新的特殊对象如下所示:

    var newSpecial = {
        date: new Date(2016, 5, 1);
        pricing: {
            isOpen: true,
            openTime: '8:00am'
        }
    };
    

    而且你知道场地 id:

    var venueId = 1234;
    

    试试这个:

    Room.findOne({venueId: venueId, 'special.date': newSpecial.date})
        .exec(function(err, roomDoc) {
            if (err) { ... }
    
            // update special if it exists
            if (roomDoc) { 
                Room.update(
                    {venueId: venueId},
                    {$set: {'special.$.pricing': newSpecial.pricing}} 
                    function(err) { ... }
                );
            }
    
            // add special if it doesn't exist
            else {
                Room.update(
                    {venueId: venueId}, 
                    {$push: {special: newSpecial}}, 
                    function(err) { ... }
                );
            }
        });
    

    这里的关键是使用'special.date' 作为查询对象中的关键,并使用positional operator 'special.$.pricing' 更新数组中正确的特殊(如果存在)。

    【讨论】:

    • 这完成了我想要的一半,但是如果查询找到了 roomDoc,我如何更新数组中与查询具有相同日期的对象?
    • 我使用 mongodb 的位置运算符添加了一些用于更新现有特殊的逻辑。试一试。
    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-08-30
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多