[英]JSON object mapping to mongoose schema _id
Ignore if this has been asked before; 忽略是否曾经被问过; I couldn't find it with my keyword searches. 我的关键字搜索找不到它。 Appreciate if someone could give some hints. 欣赏是否有人可以提供一些提示。 Learning mongoose , node js. 学习猫鼬,节点js。 I have JSON post like below 我有如下的JSON帖子
{
"_id": "711015",
"is_in_violation": true,
"is_occupied": true,
"is_out_of_service": false,
"is_reserved": false
}
The mongoose schema looks like below: 猫鼬模式如下所示:
//Create schema and model SlotSchema
const dbSchema = new Schema({
_id:
{
type: String ,
required: [true, "Id is required"]
},
is_in_violation: Boolean,
is_occupied: Boolean,
is_out_of_service: Boolean,
is_reserved: Boolean
});
In my nodejs app I have post function like below: 在我的nodejs应用程序中,我具有以下发布功能:
router.post('/v1/', function (req, res, next)
{
var postdata = new SlotSchema(req.body);
SlotSchema.create(req.body, function (err, postdata) {
if (err) return next(err);
res.json(postdata);
});
});
All of this works fine. 所有这些都很好。 Now noticed that data POST will have id instead of _id. 现在注意到数据POST将具有id而不是_id。 How can I map req.body id to my moongose schema _id. 如何将req.body id映射到我的月球计划_id。 Below is JSON which doesn't work: 以下是无法使用的JSON:
{
"id": "711015",
"is_in_violation": true,
"is_occupied": true,
"is_out_of_service": false,
"is_reserved": false
}
Thank you for your time. 感谢您的时间。 Cheers 干杯
That link gave me some idea thank you @saikat. 该链接给了我一些想法,谢谢@saikat。 Below is my solution I ended up with for now. 下面是我目前的解决方案。
router.post('/v1/', function (req, res, next)
{
console.log(req.body.id);
req.body._id = req.body.id;
var postdata = new SlotSchema(req.body);
console.log(postdata);
SlotSchema.create(postdata, function (err, postdata) {
if (err) return next(err);
res.json(postdata);
});
});
Though this was manual mapping in my opinion. 虽然在我看来这是手动映射。 It seems to serve my purpose. 这似乎符合我的目的。 I would have wanted to see, if can do automatic mapping from incoming POST to my schema. 我本来想知道是否可以将传入的POST自动映射到我的架构。 Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.