Arrays 将MongoDB集合传递给NodeJS中的数组
我在从MongoDB集合中获取数据并将其返回到NodeJS代码中的数组时遇到问题 到目前为止,代码返回了一个承诺,我不完全知道如何处理 任何帮助都将不胜感激Arrays 将MongoDB集合传递给NodeJS中的数组,arrays,node.js,mongodb,promise,Arrays,Node.js,Mongodb,Promise,我在从MongoDB集合中获取数据并将其返回到NodeJS代码中的数组时遇到问题 到目前为止,代码返回了一个承诺,我不完全知道如何处理 任何帮助都将不胜感激 async function loadData() { try { // Connect to the MongoDB cluster console.log('Attempting to connect to DB') client.connect(async err =>
async function loadData() {
try {
// Connect to the MongoDB cluster
console.log('Attempting to connect to DB')
client.connect(async err => {
const collection = client.db("db").collection("collection");
await collection.find({}).toArray().then((data) => {
//Getting stumped as the data gets returned as a promise and does not get added to an array
}
);
client.close();
console.log('Closed DB connection');
});
} catch (e) {
console.error(e);
}
您使用的承诺错误,并且
async
wait
。async/await的目的是避免使用.then
函数。选择一个,使用或
使用回调方法:
collection.find({}).toArray().then((data) => {
console.log(data);
}, err => {
// this gets called if there is an error only
console.log(err);
});
或使用异步/等待:
try {
const data = await collection.find({}).toArray();
}
catch(err) {
console.log(err);
}
请注意,如果选择使用async/await,则必须将包含函数标记为async
,您已经在这样做了。如果使用上述回调方法,则不需要这样做
Don't execute the Promise inside the loadData function
function loadData() {
try {
// Connect to the MongoDB cluster
console.log('Attempting to connect to DB')
client.connect(async err => {
const collection = client.db("db").collection("collection");
return collection.find({})
);
client.close();
console.log('Closed DB connection');
});
} catch (e) {
console.error(e);
}
打个电话获取你的数据
try {
const your_Array = await loadData().toArray();
}
catch(err) {
console.log(err);
}
对于MongoDB连接,我认为您做错了,请遵循此操作谢谢!:)但是,我必须注意,我没有使用猫鼬。相反,我使用的是官方MongoDB连接器使用ORM将为您提供比官方连接器更多的功能!