首页 文章

Mongoose编辑数组中的对象,或者如果某个属性不存在,则将其添加到数组中

提问于
浏览
0

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

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属性而不是整个对象?

1 回答

  • 0

    假设新的特殊对象看起来像这样:

    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' 更新数组中的正确特殊值(如果存在) .

相关问题