Node.js nodejs mongodb官方节点包-异步函数不会返回数据
我试图编写一个简单的函数,使用官方节点包“mongodb”,根据mongodb的匹配条件获取特定实例的id 我的功能的工作原理是我可以控制台记录数据,但我无法返回数据以使用它,正如您所看到的那样Node.js nodejs mongodb官方节点包-异步函数不会返回数据,node.js,mongodb,Node.js,Mongodb,我试图编写一个简单的函数,使用官方节点包“mongodb”,根据mongodb的匹配条件获取特定实例的id 我的功能的工作原理是我可以控制台记录数据,但我无法返回数据以使用它,正如您所看到的那样 const mongo = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; // Function for finding database id of device based on deviceKey
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);
});
为什么我的测试返回未定义,但函数中的my console.log有效?看起来您以一种奇怪的方式将回调代码与异步/等待代码结合起来。您的函数fetchId根本没有返回任何内容,这就是为什么您在获取后看不到id 试一试{ const response=等待收集。查找…toArray 返回响应[0]。\u 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);
});
logresponse[0]。\u id返回正确的id,但返回响应[0]。\u id现在返回ObjectID{u bsontype:'ObjectID',id:Buffer[92、118、15、193、186、163、208、9、82、163、110、50]},而不是实例的id?mongo中发生的lol_ID是ObjectID。如果希望它成为字符串,请调用toString。console.log将在其参数上调用toString,console.dir不会从[92、118、15、193、186、163、208、9、82、163、110、50]中调用toString。toString'hex'=='5C760FC1BAA300952A36E32'