【问题标题】:How do I merge update a document using mongoose.js?如何使用 mongoose.js 合并更新文档?
【发布时间】:2012-11-21 11:58:36
【问题描述】:

我有一个带有架构的模型:

schema = new Schema({
    name: String,
    sections: [{
        name: String,
        columns: [{
            name: String      
        }]
    }]
}];

//Lets call the model a Page

为简单起见,我检索整个模型:

app.get('/page/:name', function(req, res){
    Page.findOne( {name: req.params.name}, function(err, page){
        //error handling
        res.send page
    });
});

通过请求 GET /page/myPage 我收到:

{
    //_id, __v, etc..
    name: 'myPage',
    sections: [{
        name: 'Section 1',
        columns [{
            name: 'My #1 Column'
        }]
    }]
}

我将第 0 列的名称更改为我的 #1 列 FOOBAR!在客户端

{
    //_id, __v, etc..
    name: 'myPage',
    sections: [{
        name: 'Section 1',
        columns [{
            name: 'My #1 Column FOOBAR!'
        }]
    }]
}

另一个用户添加了一个名称为:'My #2 Column!!!'的列

   {
        //_id, __v, etc..
        name: 'myPage',
        sections: [{
            name: 'Section 1',
            columns [{
                name: 'My #1 Column'
            },
            {
                name: 'My #2 Column!!!'
            }]
        }]
    }

两个用户都将整个不同步的 JSON 发布到服务器。我想合并它们。

这是我目前的保存方法:

app.post('/page/save', function(req, res) {
  var newPage = req.body.page;

  Page.findOne({
    _id: newPage._id
  }, function(err, page) {
    if (err) {
      return res.send(err);
    }

    // this portion is obviously problematic as it doesn't merge the objects
    // it simply overwrites it with whatever page JSON you received at the time
    // of the request.
    page.sections = newPage.sections;

    page.save(function(err) {
      if (err) {
        res.send(err);
      } else {
        res.send('success!');
      }
    });

  });
});

我是否需要创建自己的更新队列,首先从服务器检索最新文档,将文档合并在一起,然后保存它们。或者这是由 mongodb 处理的。

另外,有没有像update这样的简单方法,将旧对象与新对象合并,然后保存?

谢谢。

【问题讨论】:

    标签: ajax node.js mongodb express mongoose


    【解决方案1】:

    _.merge 方法可以使用一个警告:你不能合并一个猫鼬文档,它必须是一个普通的对象,要么用.lean() 找到,要么用.toObject() 转换

    Model.update({
      _id: doc._id
    }, {
      $set: _.merge(doc.toObject(), {
        stuff: {
          hello: 'world'
        }
      })
    })
    

    【讨论】:

    • 为什么会出现这个问题?
    • @andrsnn 这样以后就没有文件了
    【解决方案2】:

    我是这样做的:

    .put('/:pr_id', (req, res, next) => {
          let pr_id = req.params.pr_id;
    
    
          PR.findById(pr_id, (err, doc) => {
            if (err) {
              return res.status(500).json({error: err});
            }
            if (!doc){
              return res.status(404).json({error: 'Document not found'});
            }
    
            let updated = req.body.pr;
            Object.assign(doc, updated);
    
            doc.save((err) => {
              if (err) {
                return res.status(500).json({error: err});
              }
    
              res.json(doc);
            });
          });
    

    Object.assign 基本上合并了两个对象(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

    【讨论】:

    • Object.assign() modifies an object in place, and so it can trigger ES6 setters. 所以 ES6 的 Object spread operator 是不可能的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多