我不太了解 Javascript,并且正在制作一個 nodejs 應用程式。我在 nodejs 中的 mongodb 查詢僅在查詢具有類似的函式方法時才有效.toArray
這是 database.js 檔案
const {MongoClient} = require('mongodb');
const uri = "mongodb srv://name:pass@clusterurl/metro4?retryWrites=true&w=majority";
// all fields are correctly filled
const client = new MongoClient(uri);
try {
// Connect to the MongoDB cluster
client.connect(err =>{
if(err) throw err;
let db = client.db('metro4');
db.collection('Station').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
});
let a = db.collection('Station').findOne({'_id':4});
if(a) {
console.log(a);
}
else{
console.log("No a\n");
}
module.exports = db;
});
} catch (e) {
console.error(e);
} finally {
client.close();
}
當我運行應用程式時,db.collection('Station').find().toArray 運行正常并輸出結果,但第二個查詢findOne不起作用。
任何幫助表示贊賞。
uj5u.com熱心網友回復:
該findOne方法回傳一個 Promise。您應該在回呼函式中處理其結果:
db.collection('Station').findOne({ _id: 4 }, function (err, a) {
if (err) {
console.log(err);
} else if (a) {
console.log(a);
} else {
console.log('No a\n');
}
});
或使用async - await:
client.connect(async (err) => {
...
let a = await db.collection('Station').findOne({ _id: 4 })
...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408218.html
標籤:
