mongoose文档更新问题
代码如下:
let WordsMetaSchema = new mongoose.Schema({
//总文档数
total: {type: Number, default: 0},
//标签对应总文档数
labels: {
厌恶: {type: Number, default: 0},
同情: {type: Number, default: 0},
喜欢: {type: Number, default: 0},
怨恨: {type: Number, default: 0},
悲伤: {type: Number, default: 0},
焦虑: {type: Number, default: 0},
愤怒: {type: Number, default: 0}
}
});
WordsMetaSchema.statics = {
getTotal$: function() {
return Promise.resolve(this.findOne({}).toObject().total);
},
add$: function(labels) {
let ctx = this;
let incs = {$inc: {total: 1}}
labels.forEach( l => {
incs.$inc['labels.'+l] = 1;
});
console.log(incs)
return this.update({}, incs);
}
};
let WordsMeta = mongoose.model('words_meta', WordsMetaSchema);
mongoose.connect('mongodb://localhost:27017/emo');
WordsMeta.add$(['厌恶', '愤怒']).then( x => {
console.log(x)
mongoose.disconnect();
});
输出结果如下:
{ '$inc': { total: 1, 'labels.厌恶': 1, 'labels.愤怒': 1 } }
{ ok: 1, nModified: 0, n: 0 }
但是查看数据库,根本没有这个words_meta
collection
1 回复
问题已经解决,生成
WordMeta
的时候,后面指定数据集就行了:
let WordsMeta = mongoose.model('WordsMeta', WordsMetaSchem, 'words_meta');