流星蒙戈 - 更新插入和$inc与aldeed简单模式 - 'update failed'



我有一个带有向前和向后按钮的图像库。点击任意一个按钮,我想在本地数据库中添加一个条目,显示图像被查看的时间(这样我以后就可以看到哪个图像被查看得最多)。

这在没有架构的情况下非常有效:

'click .btn-forward, click .btn-backward' (event, template) {
    Local.Viewed.upsert({
            imageId: this._id
        }, {
            $setOnInsert: {
                imageId: this._id,
                imageName: this.name
            },
            $inc: {
                timesViewed: 1
            }
        });
    }
});

模式:

Local.Viewed.Schema = new SimpleSchema({
    imageId: {
        type: String
    },
    imageName: {
        type: String
    },
    timesViewed: {
        type: Number,
        defaultValue: 0
    },
    createdAt: {
        type: Date,
        autoValue: function() {
            return new Date();
        }
    }
});

问题:

当我使用这个模式时,我得到一个错误:

更新失败:错误:需要查看次数在getErrorObject

架构似乎要求设置"timeViewed"。我尝试在架构中使用"defaultValue:0",但没有插入默认值0。

问题:如何使架构与此查询兼容?

谢谢你的帮助!

Muff

你试过吗

$setOnInsert: {
    imageId: this._id,
    imageName: this.name,
    timesViewed: 0
},

好的,我根据你的建议和上一个线程进行了一些讨论,这个解决方案没有错误,也没有预期的结果:

架构:

Data = {};
Data.Viewed = new Mongo.Collection("dataViewed", {});
Data.Viewed.Schema = new SimpleSchema({
    imageId: {
        type: String
    },
    userId: {
        type: String,
        autoValue: function() {
            return this.userId;
        }
    },
    imageName: {
        type: String
    },
    timesViewed: {
        type: Number
    },
    createdAt: {
        type: Date,
        autoValue: function() {
            return new Date();
        }
    }
});
Data.Viewed.attachSchema(Data.Viewed.Schema);

方法:

Meteor.methods({
    dataViewed(obj) {
        Data.Viewed.upsert({
            imageId: obj._id,
            userId: this.userId
        }, {
            $setOnInsert: {
                imageId: obj._id,
                userId: this.userId,
                imageName: obj.term,
                timesViewed: 0
            },
            $inc: {
                timesViewed: 1
            }
        });
    }
});

我认为问题是我在架构中为"timesViewed"定义了defaultValue/autoValue。此外,架构中提到的每个属性都必须在$set或$setOninsert命令中提到。

谢谢你的帮助!

最新更新