从nodejs中的json设置模型值

Bar*_*dia 1 json mongoose mongodb node.js

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

我有一个架构模型:

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

我有一个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!');
        });
      });
});
Run Code Online (Sandbox Code Playgroud)

req.body是一个json:

{
    "name":"bardia",
    "age":27,
}
Run Code Online (Sandbox Code Playgroud)

我想通过符号在代码中突出显示的位置更新foundedclient值.我想要一个假设的功能,比如.实现这一目标的最佳方法是什么?换句话说,保存为模式值的最佳方法是什么?req.body//*******//foundedclient.JsonTovalues(req.body)json

非常感谢

Nil*_*oni 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);
}
Run Code Online (Sandbox Code Playgroud)

您的客户端代码将如下所示

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!');
        });
      });
});
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助你.