我正在使用 mongoose 在我的数据库上执行 CRUD 操作。这就是我的模型的样子。
var EmployeeSchema = new Schema({
name: String,
description: {
type: String,
default: 'No description'
},
department: [],
lastUpdated: {
type: Date,
default: Date.now
}
});
部门可以包含这样的对象数组。
[
{
"id" : "55ba28f680dec4383eeebf97",
"text" : "Sales",
"topParentId" : "55ba28f680dec4383eeebf8b",
"topParentText" : "XYZ"
},
{
"id" : "55ba28f680dec4383eeebf98",
"text" : "IT",
"topParentId" : "55ba28f680dec4383eeebf8b",
"topParentText" : "XYZ"
},
{
"id" : "55ba28f680dec4383eeebf94",
"text" : "Marketing",
"topParentId" : "55ba28f680dec4383eeebccc",
"topParentText" : "ABC"
}
]
现在我需要找到 department.id = '55ba28f680dec4383eeebf94' 的所有员工,然后我需要更新对象的文本。
Employee.find({'department.id': '55ba28f680dec4383eeebf94'}, function(err, Employees) {
_.each(Employees, function (emp) {
_.each(emp.department, function (dept) {
if(dept.id === '55ba28f680dec4383eeebf94'){
dept.text = 'XXXXX'; // How to update the employee to save the updated text
}
});
});
});
用该部门的更新文本保存员工的正确方法是什么?
最佳答案
迭代代码并不是执行此操作的“敏锐”方法。最好使用 MongoDB 更新运算符,尤其是因为这里没有为数组项定义架构,所以无需担心规则:
Employee.update(
{'department.id': '55ba28f680dec4383eeebf94'},
{ "$set": { "department.$.text": "XXXXX" },
function(err,numAffected) {
// handling in here
}
);
$set
是重要的部分,否则你会覆盖整个对象。因为是 positional $
operator在语句中,因此只有匹配的(数组中的查询项)索引被更新。
另见 .find**AndUpdate()
返回修改后对象的方法的变体。
关于node.js - 如何使用点符号查找记录并使用 Mongoose 更新模式中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31741859/