【问题标题】:REST API with MongoDB Atlas, problem with findOne() while posting an entry in the DB使用 MongoDB Atlas 的 REST API,在数据库中发布条目时 findOne() 出现问题
【发布时间】: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!!!我真的不明白上面的代码有什么问题。

感谢您的帮助, 路易斯

我正在使用猫鼬。

【问题讨论】:

  • 尝试检查nullundefined,或者像这样的代码:if (! data) { // create... }
  • 感谢您的建议,已测试,但回调函数需要另一个参数错误。

标签: mongodb rest mongoose mongodb-query


【解决方案1】:

我找到了解决方案。实际上,回调函数除了数据之外,还需要一个err。 我有以下代码块:

Tea.findOne({name:req.body.name},(data) => { ... }

它必须被替换为:

Tea.findOne({ name: req.body.name }, (err, data) => {...}

然后我们将同时处理数据和错误。

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 2020-08-14
    • 2017-08-10
    • 2013-11-07
    • 2017-05-29
    • 2021-02-01
    • 1970-01-01
    • 2019-10-25
    • 2021-09-07
    相关资源
    最近更新 更多