這個問題在這里已經有了答案: Mongoose find() 回傳未定義的屬性和奇怪的物件 3 個答案 8 天前關閉。
我在 MongoDB 中有一個名為 User 的集合。集合中的每個用戶都有一個用戶名和密碼。作為 find() 查詢的結果,我得到了一個 MongoDB 檔案。現在我想在 JavaScript 中訪問檔案中的鍵值對。怎么做?到目前為止,我已經嘗試過:
const doesUserNamePasswordMatch = async (req_username,req_password) => {
const doc = await user.find({username:req_username});
console.log(doc.username);
console.log(doc.password);
if (!doc) {
return false;
}else{
if(doc.password == req_password) {
return true;
}else{
return false;
}
}
}
我上面的代碼給出了一個未定義的值。為什么?我還知道 MongoDB 中的檔案是 BSON 物件。為什么不是 JSON?那時訪問值會很容易。我只是對所有這些復雜性感到困惑和沮喪。請幫忙!
uj5u.com熱心網友回復:
請記住,該find方法回傳一個陣列。為了找到單個檔案,請findOne改用。或者只是從回傳的陣列中獲取第一個元素find:
const [doc] = await user.find({username:req_username});
此外,您可以lean在 mongoose 中使用選項來將回應轉換為純 JS 物件:
const doc = await user.findOne({username:req_username}).lean();
參考檔案:https ://mongoosejs.com/docs/tutorials/lean.html#using-lean
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504020.html
標籤:javascript mongodb 猫鼬
下一篇:貓鼬,更新的嵌套陣列
