我正在嘗試使用 nodejs 使用 Mongoose for MongoDB 設定資料庫。目前,當它執行 findByID 時,它回傳一個我似乎無法決議或轉換為字串的物件。我正在嘗試將提供的用戶 ID 與回傳的值進行比較,如下所示。如何執行 FindBy.. 函式并以字串格式獲取結果,以便進行比較?謝謝
globalTest = doc._id;
//const foundUser = Auth.findById(mongoose.Types.ObjectId(doc._id));
const foundUser = Auth.findById(mongoose.Types.ObjectId(globalTest));//.lean().exec();
if(globalTest===foundUser){
console.log('match');
}else{
console.log('no match');console.log(foundUser ' vs ' globalTest);
}
console.log('BREAK: ' foundUser._id);//always undefined
和控制臺輸出:
Saving: 622f6ed69f5b04b4c82fce74 no match
auth.findOne({ _id: new ObjectId("622f6ed69f5b04b4c82fce74") }) vs 622f6ed69f5b04b4c82fce74
BREAK: undefined
uj5u.com熱心網友回復:
根據您的控制臺輸出foundUser回傳查詢,您需要執行它才能運行查詢并獲取資料。
我假設你正在使用async/await
const foundUser = await Auth.findById(mongoose.Types.ObjectId(globalTest)).lean().exec();
if (globalTest == foundUser._id) {
console.log('match');
} else {
console.log('no match')
}
回呼版本
Auth.findById(mongoose.Types.ObjectId(globalTest)).lean().exec((err, doc) => {
if(err) console.error(err);
if (globalTest == doc._id) {
console.log('match');
} else {
console.log('no match')
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443519.html
