我尝试通过查找特定的“ _id”来查询MongoDB,但新的ObjectID不能解决问题。我尝试通过“ var obj = new ObjectID()”创建一个包含随机ObjectID的变量,但效果不佳。然后,我检查我的MongoDB版本,它是最新版本(数据库版本v4.0.2)。服务器连接工作正常。有什么想法吗?谢谢。
我的收藏集:
[
{
"_id": "5bc9fe6683dfb93706fe8a24",
"name": "Luis",
"occupation": "Doctor"
},
{
"_id": "5bc9fe6683dfb93706fe8a25",
"name": "Peter",
"occupation": "Student"
}
]
Mangodb代码:
const {MongoClient} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017/NewApp',(err, client) => {
if(err){
return console.log("Unable to connect to MongoDB server");
}
console.log("Connect to MongoDB server");
const db = client.db('NewApp');
db.collection('Users').find({"_id": new ObjectID("5bc9fe6683dfb93706fe8a24")}).toArray().then((data) => {
console.log(JSON.stringify(data, undefined, 2));
},(error) => {
if(error){console.log("Unable to fetch the data", error)}
});
client.close();
});
错误:
Connect to MongoDB server
/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
throw err;
^
ReferenceError: ObjectID is not defined
at MongoClient.connect ...
答案 0 :(得分:2)
只需将代码的第一行替换为
const { MongoClient, ObjectID } = require('mongodb');
您需要导入ObjectID
类才能使用它。
您可以在此处查看所有出口的列表:
https://github.com/mongodb/node-mongodb-native/blob/master/index.js