簡體   English   中英

MongoDB 查詢與 promise 未執行 if 語句(MongoDB node.js 驅動程序)

[英]MongoDB query with promise not executing if statement (MongoDB node.js driver)

我試圖弄清楚為什么在找不到文檔時不執行 if(,document) ? 但相反,應用程序直接跳轉到 catch 塊並返回 500 狀態?

澄清一下,通過 req.body.id 發送的 id 沒有問題,如果我發送與 db 中的文檔匹配的有效 ID,則會執行成功塊。 問題是當我發送一個與文檔不匹配的 ID 時, if (,document) {} 塊不會被執行。 而是執行了 catch 塊。

我的意圖是這樣(如果代碼示例不夠清楚):

如果找不到文檔返回:return res.status(401).json({ message: 'Unauthorized.' }

如果找到文檔:return res.status(200).json({ message: 'Authorized.' });

如果有數據庫/服務器錯誤:return res.status(500).json({ message: 'Internal server error.' })

下面的小代碼示例:

const login = (req, res) => {
    userSchema
        .findById(req.body.id)
        .then((document) => {
            if (!document) {
                return res.status(401).json({ message: 'Unauthorized.' }).end();
            }
            return res.status(200).json({ message: 'Authorized.' });
        })
        .catch((err => return res.status(500).json({ message: 'Internal server error.' });
};

為了成功執行這部分:

userSchema
        .findById(req.body.id)
          ...

req.body.id必須是可轉換為 ObjectId 的值。 否則你會看到這個錯誤CastError: Cast to ObjectId failed for value... ,這當然會觸發catch塊。

因此,例如,如果req.body.id604156ee6db28527531bd612 ,它完全可以轉換為 ObjectId,您的查詢將實際執行,如果沒有找到結果,將觸發您的if塊。

但是,如果req.body.idsh21343dfs或空字符串,則findById將拋出上面提到的CastError並將您發送到 catch 塊中。

因此,只需使用 catch 作為提示發送回User Not Found錯誤之類的內容,因為很少有其他事情可以觸發findById中的 catch 塊

或者您可以像這樣明確地檢查字符串的有效性:

const ObjectID = require('mongodb').ObjectID;
...
...
if(ObjectID.isValid(req.body.id))
    return res.status(401).json({ message: 'Unauthorized.' }).end();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM