如何使用点符号查找记录并使用猫鼬更新模式中的值

How to find a record using dot notation & update the value in a schema using mongoose

我正在使用 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
        }
      });

    });

  });

用该部门的更新文本保存员工的正确方法是什么?

我认为你可以使用 update 模型:

Employee.update({department.id: '55ba28f680dec4383eeebf94'}, {department.text: 'XXXXX'}, {multi: true}, 
    function(err, num) {
        console.log("updated "+num);
    }
);

第一个对象是查询,查找什么:{department.id: '55ba28f680dec4383eeebf94'},第二个是更新,更新什么:{department.text: 'XXXXX'} 第三个是传递给更新的选项, multi 表示更新您找到的每条记录:{multi: true}

迭代代码不是执行此操作的 "sharp" 方法。最好使用 MongoDB 更新运算符,尤其是因为这里没有为数组项定义模式,所以不用担心规则:

Employee.update(
    {'department.id': '55ba28f680dec4383eeebf94'},
    { "$set": { "department.$.text": "XXXXX" },
    function(err,numAffected) {
       // handling in here
    }
);

语句中的$set is the important part, otherwise you overwrite the whole object. As is the positional $ operator,所以只更新匹配的(数组中的查询项)索引。

另请参阅 .find**AndUpdate() 变体以了解 return 修改对象的方法。