尝试使用Sails.js和Waterline ORM更新MongoDB子文档中的单个键时遇到问题。这就是我的person.js
模型:
module.exports = {
attributes: {
name: { type: 'string', required: true },
favorites: {
type: 'json',
defaultsTo: {
color: null,
place: null,
season: null
}
}
}
}
现在,让我们说我想从我的控制器更新一个特定的人的名字和最喜欢的季节,我这样做:
Person.update({ id: '1' }, {
name: 'Dan',
favorites: {
season: 'Summer'
}
}).exec(function(error, updatedPerson) {
console.log(updatedPerson);
});
当我运行它时,favorites
对象完全被替换为只更新了我更新的一个键(季节键)而不是保留其他两个键(颜色和位置),而只更新了一个我想。我错过了什么?如何让它只更新我指定的密钥?
答案 0 :(得分:1)
您可以在模型上使用 .native()
方法直接访问mongo驱动程序,然后使用 $set
运算符更新独立的领域。但是,您需要首先将对象转换为具有点符号的单级文档,如
{
"name": "Dan",
"favorites.season": "Summer"
}
以便您可以将其用作:
var criteria = { "id": "1" },
update = { "$set": { "name": "Dan", "favorites.season": "Summer" } },
options = { "new": true };
// Grab an instance of the mongo-driver
Person.native(function(err, collection) {
if (err) return res.serverError(err);
// Execute any query that works with the mongo js driver
collection.findAndModify(
criteria,
null,
update,
options,
function (err, updatedPerson) {
console.log(updatedPerson);
}
);
});
要转换需要更新的原始对象,请使用以下函数
var convertNestedObjectToDotNotation = function(obj){
var res = {};
(function recurse(obj, current) {
for(var key in obj) {
var value = obj[key];
var newKey = (current ? current + "." + key : key); // joined key with dot
if (value && typeof value === "object") {
recurse(value, newKey); // it's a nested object, so do it again
} else {
res[newKey] = value; // it's not an object, so set the property
}
}
})(obj);
return res;
}
然后您可以在更新中调用
var criteria = { "id": "1" },
update = { "$set": convertNestedObjectToDotNotation(params) },
options = { "new": true };
查看下面的演示。
var example = {
"name" : "Dan",
"favorites" : {
"season" : "winter"
}
};
var convertNestedObjectToDotNotation = function(obj){
var res = {};
(function recurse(obj, current) {
for(var key in obj) {
var value = obj[key];
var newKey = (current ? current + "." + key : key); // joined key with dot
if (value && typeof value === "object") {
recurse(value, newKey); // it's a nested object, so do it again
} else {
res[newKey] = value; // it's not an object, so set the property
}
}
})(obj);
return res;
}
var update = { "$set": convertNestedObjectToDotNotation(example) };
pre.innerHTML = "update = " + JSON.stringify(update, null, 4);
<pre id="pre"></pre>
答案 1 :(得分:0)
只需更改您的查询:
Person.update({ id: '1' },{ name: 'Dan',favorites: { $set: {season: Summer'}}}})