Bạn có thể sử dụng mã .native () >
trên mô hình của bạn có quyền truy cập trực tiếp vào trình điều khiển mongo và sau đó là $ set
toán tử để cập nhật các trường một cách độc lập. Tuy nhiên, trước tiên bạn cần chuyển đổi đối tượng thành tài liệu một cấp có ký hiệu dấu chấm như
{
"name": "Dan",
"favorites.season": "Summer"
}
để bạn có thể sử dụng nó như:
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);
}
);
});
Để chuyển đổi đối tượng thô cần được cập nhật, hãy sử dụng hàm sau
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;
}
mà sau đó bạn có thể gọi trong bản cập nhật của mình là
var criteria = { "id": "1" },
update = { "$set": convertNestedObjectToDotNotation(params) },
options = { "new": true };
Kiểm tra bản trình diễn bên dưới.
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>