【发布时间】: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