gpt4 book ai didi

javascript - Node js Rest Service将数据保存到特定的对象json中

转载 作者:可可西里 更新时间:2023-11-01 10:38:21 26 4
gpt4 key购买 nike

我正在使用 Node JS 开发 REST API。我已经开发了 post 请求,但不要尝试将数据保存在 MongoDB Schema 的特定对象上。我有这个 MongoDB 模式

var ProfileSchema = db.Schema({
farmId: { type: String, required: true },
companyName: { type: String, required: true },
firstname: {type: String, required: true},
surname: {type: String, required: true},
address: {type: String, required: true},
city: {type: String, required: true},
state: {type: String, required: false},
postalcode: {type: String, required: true},
country: {type: String, required: true},
telephone: {type: String, required: true},
email: {type: String, required: true},
demographics:{
farmSize: {type: String, required: true },
crops: {type: String, required: true},
liveStock: {type: String, required: true},
precisionFarming: {type: String, required: true},
currentTire: {type: String, required: false}
}
});

这是我的发帖请求:

router.post('/profile', VerifyToken, function (req, res) {
Profile.create({
farmId:req.body.farmId,
companyName:req.body.companyName,
firstname:req.body.firstname,
surname: req.body.surname,
address: req.body.address,
city: req.body.city,
state: req.body.state,
postalcode: req.body.postalcode,
country: req.body.country,
telephone: req.body.telephone,
email: req.body.email,
farmSize: req.body.farmSize,
crops: req.body.crops,
liveStock: req.body.liveStock,
precisionFarming: req.body.precisionFarming,
currentTire: req.body.currentTire
},
function (err, profile) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send({status: 'ok', data: { msg: 'Profile saved'}});

});
});

如何将数据保存到“人口统计”对象中?我的代码给出错误 500。请提供任何帮助,这对我解决此问题非常重要。

最佳

此错误日志:

{ ValidationError: ProfileFarm validation failed:    demographics.precisionFarming: Path `demographics.precisionFarming` is     required., demographics.liveStock: Path `demographics.liveS
tock` is required., demographics.crops: Path `demographics.crops` is required., demographics.farmSize: Path `demographics.farmSize` is required.

最佳答案

你能记录你的req.body吗?

您的模式定义有几个字段标记为必填,恐怕您没有传递给它们或者它们未定义,例如:crop、liveStock 等您可以执行以下操作:

  • 正确发送所有数据

或者

  • 只需更改模式定义并删除所需的标志,或将它们设置为 false 即可开始工作。

关于javascript - Node js Rest Service将数据保存到特定的对象json中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52138131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com