我尝试在nodejs中查询MongoDB,以获取我使用的_id x的数据
async function getTestData(id){
return new Promise((resolve, reject) => {
MongoClient.connect(uri, { useNewUrlParser: true, keepAlive: 1 }, function(err, client) {
const dbo = client.db("test");
var query = { _id: id };
dbo
.collection("smscripts")
.find(query)
.project({ 'data' : 1})
.toArray(function(err, items) {
err
? reject(err)
: resolve(items);
});
});
});
}查询为
{ _id: '5dada7dfdca94dbaf65d9547' }但是我总是得到一个空数组。有人能帮我解释一下为什么数组总是空的吗?顺便说一句,err是空的。该id绝对存在。
发布于 2019-10-22 19:42:18
在mongo db中,_id以ObjectId为前缀
所以你首先需要价值,试试这个
id = ObjectId("507c7f79bcf86cd7994f6c0e")然后将其与ID进行比较。
希望能有所帮助
发布于 2019-10-22 20:53:16
在您的代码“var import { ObjectId } from "bson"
var query = { '_id' : ObjectId(id) }
await关键字。
const client =等待MongoClient.connect(uri,{ useNewUrlParser: true,keepAlive: 1 }) .catch(err => { console.log(err);});if (!client)返回;
尝试{
const dbo =client.db(‘dbo.collection’);让集合= dbo.collection('smscripts');让查询={ '_id‘:ObjectId(id) };让投影={ 'data’:1};让游标=等待collection.find(查询,投影).toArray();console.log(游标);返回游标;} catch (err) { console.log(err);} finally { client.close();}
https://stackoverflow.com/questions/58503277
复制相似问题