这是我的架构:
var Account = new Schema({
username: String,
likes: Schema.Types.Mixed
})
在这里,我将'someProperty'属性添加到喜欢中。一切都很好。
var conditions = {'_id':req.body.id};
var update = {'$set':{'likes.someProperty': req.body.something}};
var callback = function (err, data) {
if (err) return next(err);
};
users.update(conditions, update, callback);
更新我的文档后:
'username': Fat Gandalf,
'likes': {
someProperty: '100'
}
我的问题是我不知道“someProperty”的名称。我需要以某种方式动态创建它:
var temp = 'likes.' + req.body.propertyName; // -- > 'likes.anything'
var update = {'$set':{temp: req.body.something}};
上面的例子不起作用。他妈的!需要您的帮助!
最佳答案
使用square bracket notation 构造字段对象如下:
var conditions = { "_id": req.body.id },
update = { "$set": {} };
update["$set"]["likes."+req.body.propertyName] = req.body.something;
Users.update(conditions, update, callback);
或者使用computed property names (ES6) :
var conditions = { "_id": req.body.id },
update = {
"$set": {
["likes."+req.body.propertyName]: req.body.something
}
};
Users.update(conditions, update, callback);
关于node.js - Mongoose:使用 Schema.Types.Mixed 动态创建键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35799969/