本文介绍了Lodash与猫鼬合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个使用express.js和mongoose的更新方法的代码片段。
我试图将现有的mongo实体与请求负载体中的json对象合并。

Here is a code snippet of an update method using express.js and mongoose.I'm trying to merge the existing mongo entity with the json object from the request payload body.

exports.update = function(req, res) {
    if(req.body._id) { delete req.body._id; }
    Entity.findById(req.params.id, function (err, entity) {
        if (err) { return handleError(res, err); }
        if(!entity) { return res.send(404); }
        var updated = _.merge(entity, req.body);
        updated.save(function (err) {
            if (err) { return handleError(res, err); }
            return res.json(200, entity);
        });
    });
};

这不幸没有起作用。我收到这个错误

This unfortunately doesn't work. I'm getting this error

node_modules/mongoose/lib/document.js:1272
    doc.save(handleSave);
        ^
TypeError: Object #<Object> has no method 'save'

我已经尝试创建自己的自定义 merge 方法,但仍然无法实现正确的合并:

I have try to create my own custom merge method but still i cannot achieve a proper merge :

exports.update = function(req, res) {
    if(req.body._id) { delete req.body._id; }
    Entity.findById(req.params.id, function (err, entity) {
        if (err) { return handleError(res, err); }
        if(!entity) { return res.send(404); }
        var updated = merger(resume, req.body)//_.merge(resume, req.body);
        updated.save(function (err) {
            if (err) { return handleError(res, err); }
            return res.json(200, entity);
        });
    });
};
function merger (a, b) {
    if (_.isObject(a)) {
        return _.merge({}, a, b, merger);
    } else {
        return a;
    }
};

有了这个差异,我有这个消息:

With this variance i'm having this message :

node_modules/mongoose/lib/document.js:1245
      return self.getValue(i);
              ^
TypeError: Object #<Object> has no method 'getValue'

因此,我无法扩展 entity req.body 到目的地已更新。只有结构被复制我猜。有些人请让我知道我错了什么。谢谢。

As a result, I am not able to extend the values of entity, and req.body to the destination updated. Only the structure gets copied i guess. Some one please let me know where I am wrong. Thanks.

推荐答案

我可以通过更改 _来解决这个问题。 >到 _。extends ,然后直接在 findById 返回的结果上调用save,而不是变量更新

I was able to fix this by changing _.merge to _.extend, then calling save directly on the results returned by findById instead of the variable updated.

exports.update = function(req, res) {
    if(req.body._id) { delete req.body._id; }
    Entity.findById(req.params.id, function (err, entity) {
        if (err) { return handleError(res, err); }
        if(!entity) { return res.send(404); }
         _.extend(entity, req.body);
        entity.save(function (err) {
            if (err) { return handleError(res, err); }
            return res.json(200, entity);
        });
    });
};

这篇关于Lodash与猫鼬合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:19