【发布时间】:2018-11-27 17:57:19
【问题描述】:
您好,我有将数据发布到 mongodb 的终点,当我提交表单时,我认为只提交了 ID,因为我使用的是插入而不是保存,
这是它的外观:
app.post('/comments', (req, res) => {
const { errors, isVal } = validate(req.body);
if (isVal){
const { author, description } = req.body;
db.collection('comments').insert({ author, description }, (error, result) => {
if (error) {
res.status(500).json({ errors: { global: "Oops something is right!" }});
} else {
res.json({ comments: result.ops[0] });
}
})
} else {
res.status(400).json({ errors });
}
});
上面的方法是只保存ID,其他数据保存为null:我尝试这样更改,将insert替换为save some one,建议类似这样。
app.post('/comments', (req, res) => {
const { errors, isVal } = validate(req.body);
if (isVal){
const { author, description } = req.body;
db.collection('comments').save({ author, description }, (error, result) => {
if (error) {
res.status(500).json({ errors: { global: "Oops something is right!" }});
} else {
res.json({ comments: result.ops[0] });
}
})
} else {
res.status(400).json({ errors });
}
});
还是一样:这是保存在数据库中的结果:
{
"_id": {
"$oid": "5b281457f5b629565c09ce26"
},
"author": null,
"description": null
}
如何更改我的方法以便它可以使用保存而不是插入? mongodb中的save和insert有什么区别?
【问题讨论】:
标签: javascript node.js mongodb typescript