我正在使用expressjs,mongodb和mongoose,我正在尝试更新以下架构的计数对象:
var UsersSchema = new Schema({
username: { type: String, required: true },
counts: {
followers: { type: Number, default: 0 },
trips: { type: Number, default: 0 },
videos: { type: Number, default: 0 }
}
})
更新部分(不工作):
var key = 'trips' // set dynamically, could be 'videos' or 'followers'
Users.update({'username': username}, {$set: {'counts.key': 12}}, callback)
工作示例但不是动态的:
Users.update({'username': username}, {$set: {'counts.trips': 12}}, callback)
有什么想法吗?
答案 0 :(得分:2)
您可以为$ set创建动态变量并在查询中使用。
var key = 'trips';
var dynSet = {$set: {}};
dynSet.$set["counts." + key] = 12;
Users.update({'username': username}, dynSet, callback)