【问题标题】:set model values from json in nodejs在nodejs中从json设置模型值
【发布时间】:2018-12-13 04:05:27
【问题描述】:

大家好,我想知道如何将 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,
}

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

非常感谢

【问题讨论】:

  • 为什么 req.body JSON 字符串?如果您正确设置正文解析器,它应该是一个对象。
  • 确实是 JSON 对象。我的问题是如何将其值分配给我的客户值。

标签: json node.js mongodb mongoose


【解决方案1】:

您可以定义一个类似于 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!');
        });
      });
});

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 2014-03-28
    • 2019-06-08
    • 1970-01-01
    • 2022-01-23
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多