在nodejs中从json设置模型值

时间:2018-07-04 17:06:36

标签: json node.js mongodb mongoose

大家好,我想知道如何将json字符串保存到猫鼬模型对象中吗? 让我解释一下我的问题的简化版本:

我有一个模式模型:

const mongo = require('mongoose');
const clientSchema = mongo.Schema({
    name: {type: String},
    age: {type: Number},
    updated_at: {type: Date},
}

我有一个put方法,如下所示:

var Client = mongo.model('client', clientSchema);

//Update User
server.put(`/api/clients/:_id`, (req, res) =>
{
    Client.model.findById(req.params._id, (err, foundedclient) => 
    {
        if(err) res.send(err);

        //***********************************************************//
        /*I want to update foundedclient from req.body here!         */
        /*some function like : foundedclient.JsonTovalues(req.body); */  
        //***********************************************************//

        foundedclient.updated_at = new Date().toISOString();

        foundedclient.save((err) =>
        {
            res.send('saved successfully!');
        });
      });
});

req.body是一个json:

{
    "name":"bardia",
    "age":27,
}

我想从foundedclient的{​​{1}}值开始更新到我在代码中以req.body符号突出显示的位置。我想要一个假设函数,例如//*******//。最好的方法是什么?换句话说,将foundedclient.JsonTovalues(req.body)保存为模式值的最佳方法是什么?

非常感谢

1 个答案:

答案 0 :(得分:5)

您可以将实例方法定义为类似于 updateByJson 的方法,如下所述

const clientSchema = mongo.Schema({
   name: {type: String},
   age: {type: Number},
   updated_at: {type: Date},
}

// here simply calling update method internally but exposed as an instance method 
clientSchema.methods.updateByJson = function(jsonToUpdate, cb){
   // will work if you are using mongoose old version 3.x
   this.constructor.update({_id: this._id}, {$set:jsonToUpdate}, cb);
   // should work with latest versions
   this.model('client').update({_id: this._id}, {$set:jsonToUpdate}, cb);
}

您的客户代码将如下所示

var Client = mongo.model('client', clientSchema);

//Update User
server.put(`/api/clients/:_id`, (req, res) =>
{
    Client.model.findById(req.params._id, (err, foundedclient) => 
    {
        if(err) res.send(err);

        jsonToUpdate = req.body
        jsonToUpdate.updated_at = new Date().toISOString();

        foundedclient.updateByJson(jsonToUpdate, (err) => {
            res.send('saved successfully!');
        });
      });
});

希望对您有帮助。