NodeJS MongoDB 官方节点包 - 异步函数不会返回数据



我正在尝试编写一个简单的函数,使用官方节点包"mongodb"根据mongodb的匹配标准获取特定实例的id。

我的函数工作,因为我可以控制台记录数据,但我无法return数据以使用它,如您所见。

const mongo = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
// Function for finding database id of device based on deviceKey, The database is written into 
// the code under the const 'db' as is the collection.
async function fetchId(deviceKey) {
const client = await mongo.connect(url, { useNewUrlParser: true });
const db = client.db('telcos');
const collection = db.collection('device');
try {
await collection.find({"deviceKey": deviceKey}).toArray((err, response) => {              
if (err) throw err;
console.log(response[0]._id);   // << works logs _id
return response[0]._id;         // << does nothing... ?
})
} finally {
client.close();
}
}
// # fetchId() USAGE EXAMPLE
//
// fetchId(112233);   < include deviceKey to extract id
//
// returns database id of device with deviceKey 112233
// Run test on fetchId() to see if it works
fetchId("112233")
.then(function(id) {
console.dir(id); // << undefined
})
.catch(function(error) {
console.log(error); 
});

为什么我的测试返回undefined但我在函数中的console.log()有效?

看起来你以一种奇怪的方式将回调代码与异步/等待代码结合起来。您的函数fetchId根本没有返回任何内容,这就是为什么您在获取后看不到id的原因。

try {
const response = await collection.find(...).toArray()
return response[0]._id
}...

如果我们无法等待collection.find(...).toArray()并且需要手动将其从使用回调转换为承诺,则必须执行以下操作:

function fetchId (id) {
// this function returns a promise
return new Promise((resolve, reject) => {
...
collection.find(...).toArray((err, response) => {
// within the callback, returning values doesn't do anything
if (err) return reject(err);
return resolve(response[0]._id);
})
});
}

您正在返回一个值,但处理方式就像返回承诺一样。请尝试此代码。我没有测试过它。

const mongo = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
// Function for finding database id of device based on deviceKey, The database is written into 
// the code under the const 'db' as is the collection.
async function fetchId(deviceKey) {
return new Promise((resolve,reject)=>{
const client = await mongo.connect(url, { useNewUrlParser: true });
const db = client.db('telcos');
const collection = db.collection('device');
try {
await collection.find({"deviceKey": deviceKey}).toArray((err, response) => {              
if (err) throw err;
console.log(response[0]._id);   // << works logs _id
return resolve(response[0]._id);         // << does nothing... ?
})
}
catch(error){
return reject(error);
}
finally {
client.close();
}
});
}
// # fetchId() USAGE EXAMPLE
//
// fetchId(112233);   < include deviceKey to extract id
//
// returns database id of device with deviceKey 112233
// Run test on fetchId() to see if it works
fetchId("112233")
.then(function(id) {
console.dir(id); // << undefined
})
.catch(function(error) {
console.log(error); 
});

最新更新