Meteor Mongo - upsert和$ inc with aldeed simple schema - ' update failed'

时间:2016-04-12 13:43:15

标签: mongodb meteor meteor-collection2 simple-schema

我有一个带前进和后退按钮的图库。点击其中一个按钮,我想在本地数据库中插入一个条目,查看图像的次数(这样我以后可以看到哪个图像被查看最多)。

完全没有架构:

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

问题:

当我使用此Schema时,我收到错误:

  

更新失败:错误:需要查看时间       at getErrorObject

Schema似乎要求' timesViewed'已设定。 我尝试使用' defaultValue:0'在Schema中,但是没有插入默认值0.

问题:如何让Schema与此查询兼容?

感谢您的帮助!

莫夫

2 个答案:

答案 0 :(得分:1)

你试过吗

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

答案 1 :(得分: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
            }
        });
    }
});

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

感谢您的帮助!