【发布时间】:2021-11-29 17:03:48
【问题描述】:
尝试使用 MongoDB Atlas 开发 REST API。这个想法是如果数据库中不存在 request.body.name ,则将新项目 POST 到 DB 中。
// POST '/tea'
const newTea = (req, res) => {
// check if the tea name already exists in db
Tea.findOne({name:req.body.name},(data) => {
console.log(`The req.body.name is: ${req.body.name}`);
console.log(`The value of data is: ${data}`);
//if tea not in db, add it
if (data === null) {
//create a new tea object using the Tea model and req.body
const newTea = new Tea({
name:req.body.name,
image: req.body.image, // placeholder for now
description: req.body.description,
keywords: req.body.keywords,
origin: req.body.origin,
brew_time: req.body.brew_time,
temperature: req.body.temperature,
})
// save this object to database
newTea.save((err, data)=>{
if(err) return res.json({Error: err});
return res.json(data);
})
// if tea is in db, return a message to inform it exists
} else {
return res.json({message:`The Tea with the name: ${data.name} already exists`});
}
})
};
问题是每当我发布一个新的茶 (newTea),如果茶已经存在于数据库中(findOne 通过它的名称),它会返回一个新的数据库条目,而不是一条消息说具有该名称的茶已经存在了。
如果我们console.log数据的值,从Tea.findOne的值是null!!!我真的不明白上面的代码有什么问题。
感谢您的帮助, 路易斯
我正在使用猫鼬。
【问题讨论】:
-
尝试检查
null和undefined,或者像这样的代码:if (! data) { // create... }。 -
感谢您的建议,已测试,但回调函数需要另一个参数错误。
标签: mongodb rest mongoose mongodb-query