node.js - 如何使用点符号查找记录并使用 Mongoose 更新模式中的值

标签 node.js mongodb mongoose mean.io

我正在使用 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/

相关文章:

node.js - NodeJS https 客户端错误 - 400

node.js - 只是无法解决 CORS 问题

javascript - Node 坚持重型 Node.js 应用程序不返回值

java - Spring Data Mongo @Indexed 多次创建索引

javascript - Meteor 方法成功更新了数据库,但向 Meteor.call 返回 500 错误

node.js - nodejs v0.12 和 v5.x 发行版之间的区别

mongodb - 使用 MongoDB 创建新的 Strapi 项目时,是什么导致错误 "Connection test failed: spawn npm; ENOENT"?

node.js - Mongoose 不从集合中删除对象

javascript - 选择 Mongoose 模式中的所有字段

node.js - Mongoose - 通过 findOne() 搜索架构失败