[英]ASYNC AWAIT function .find() mongodb
How can i save a variable from async function .find from mongodb ?如何从异步function中保存变量。从mongodb中查找? Inside the function console.log its working (prints the right value) and outside the function it is undefined.
在 function console.log 内部它的工作(打印正确的值)和在 function 外部它是未定义的。
var list;
MongoClient.connect(uri, function(err, db) {
var dbc = db.db("chat");
dbc.collection("chat_messages").find({user1: data.from, user2: data.to}).toArray(function (err, result){
console.log(result[0].msgs); <---- here its working
list = result[0].msgs;
});
db.close();
});
console.log(list); <---- here its not working
Here's how you would do it with async await.这是使用异步等待的方法。
async function getList() {
let db = await MongoClient.connect(url);
let dbo = db.db("testdb");
return await dbo.collection("cars").find({}, { projection: { _id: 0, name: 1} }).toArray()
}
listCars().then(cars => {
console.log(cars); //You will get your results here
})
The mongoDB queries in nodejs like the one above are asynchronous so you cannot get the return value in a variable directly. nodejs 中的 mongoDB 查询(如上面的查询)是异步的,因此您无法直接在变量中获取返回值。 You either have to use a callback function or.then() to use promises like in the example above.
您要么必须使用回调 function 或 .then() 才能使用上面示例中的承诺。
The toArray() function you are using is a MongoDB method, the one you mentioned in your question is a jQuery one.您正在使用的 toArray() function 方法是 MongoDB 方法,您在问题中提到的方法是 jQuery 方法。 This is the correct documentation for your reference -> https://docs.mongodb.com/manual/reference/method/cursor.toArray/
这是供您参考的正确文档-> https://docs.mongodb.com/manual/reference/method/cursor.toArray/
You need to make the entire code block into an async-await
code block, or take in the help of then
block您需要将整个代码块变成一个
async-await
代码块,或者借助then
块的帮助
let conn = await client.connect(url);
let db = conn.db("test");
const results = await db.collection("cars").find({}, { projection: { _id: 0, name: 1} }).toArray()
here results
will have your output这里的
results
将有你的 output
try work with Promises, look that sample:尝试使用 Promises,查看该示例:
const list = new Promise(function (resolve, reject) {
MongoClient.connect(uri, function(err, db) {
var dbc = db.db("chat");
dbc.collection("chat_messages").find({user1: data.from, user2: data.to}).toArray(function (err, result){
if(err) {
reject(err);
} else {
resolve(result);
}
db.close();
});
});
});
Then use as promise if you need:然后根据需要使用 promise:
list.then(arrayList => {
console.log(arrayList[0].msgs);
}).catch(err => console.log(err.message));
OR, force to run sync或者,强制运行同步
const msgs = (await list)[0].msgs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.