我创建了一个nodejs API,您可以在其中通过POST推送新条目,如果该条目已经存在,它应该更新它。
现在我遇到一个问题,我通过 mongoose 的 findOne()
检查该条目是否已存在,但它不会触发更新功能。
这是代码:
通过 POST 的入口点:
exports.create_a_status = function(req, res) {
if(read_status(req.body.hostname)){
console.log("update")
update(req,res)
}
else{
var new_status = new Status(req.body);
new_status.save(function(err, status) {
if (err)
res.send(err);
history.create_a_history(req.body);
res.json(status);
});
}
}
检查条目是否存在:
const read_status = function(hostname){
Status.findOne({hostname: hostname},function(err,status){
console.log(hostname)
if (status){
console.log(status)
return status;
}
return;
})
}
和更新函数,但这不会从 create_a_status()
触发:
exports.update = function(req, res) {
// Update a status identified by the hostname in the request
Status.findOneAndUpdate({hostname: req.params.hostname}, req.body,{new:true})
.then((updatedStatus) => {
res.json(updatedStatus);
})
.catch((err)=>{
res.send(err);
});
};
提前致谢!
最佳答案
我解决了这个问题:
exports.update_a_status = function(req, res) {
// Update a status identified by the hostname in the request
Status.findOneAndUpdate({hostname: req.body.hostname}, req.body,{upsert: true, new: true, runValidators: true})
.then((updatedStatus) => {
res.json(updatedStatus);
})
.catch((err)=>{
res.send(err);
});
};
重点是 findOneAndUpdate()
函数中的选项,其中我没有设置 upsert: true
这意味着如果它没有通过主机名找到条目,它只会创建它。
关于javascript - Nodejs API 决定是创建还是更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915195/