我在使用 MongoDB 控制臺時遇到問題。只記錄集合的一個資料。我已經搜索了無數關于此的主題,但沒有一個完全符合我的要求。我想從我的貓鼬資料庫中獲取一個數字資料。(我正在創建一個 discord.js bot)這是資料庫的樣子:
_id: 61bb8dc5a23c9a077066abf0
user: "soki#2400"
userId: "466270219132731392"
amount: 16
__v: 0
我要console.log()的價值amount。
這是我現在的代碼:
console.log(giftsSchema.find({"_id": 0},{"user": msg.author.tag},{"userId": msg.author.id}).amount);
所以我希望它列印的是:
16
但它列印
undefined
uj5u.com熱心網友回復:
我認為您的意思是在兩個欄位user和userId. 你應該使用這個:
giftsSchema.findOne(
{"user": msg.author.tag, "userId": msg.author.id}, // query
function (err, user) {
console.log(user.amount);
});
如果您想使用投影以便僅回傳金額欄位,則提供第二個引數,其中包含您想要 1 而不需要 0 的欄位。
giftsSchema.findOne(
{"user": msg.author.tag, "userId": msg.author.id}, // query
{_id: 0, amount: 1}, // projection
function (err, user) {
console.log(user.amount);
});
在您的例子您所提供的3個引數{"_id": 0},{"user": msg.author.tag}和{"userId": msg.author.id}。隨著find()方法的第一個引數是查詢/過濾器。因此,在您的代碼中,您正在查詢_id= 0 的所有記錄,我認為您不想要那樣。第二個引數用于投影,并且您為此提供了一個無效物件,投影值應該只有 1 或 0,就像您的第一個引數一樣。第三個引數用于選項,在這里不起作用。
您想通過將它們放在像這樣的單個物件中來查詢多個欄位{ field1 : value1, field2 : value2 }。我也認為你只想要一個結果,所以你應該使用findOne()來代替,這樣你只會得到一個物件,而不是一個物件陣列。
此外,Mongoose 是異步的。所以你應該創建一個async函式和await結果。或者您可以提供一個回呼函式,如我的示例所示。注意:err在我的例子中我不處理這種情況。
uj5u.com熱心網友回復:
.find()方法將回傳一個 Promise。在記錄結果之前,您應該首先等待該 Promise 解決。嘗試這樣做:
const someFunction = async () => {
let result = await giftsSchema.find({
"user": msg.author.tag, "userId": msg.author.id
}, {
_id: 0, amount: 1
});
console.log('Result: ', result.amount);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/384735.html
標籤:javascript MongoDB 猫鼬 不和谐.js 猫鼬模式
