为什么在Mangodb中未定义ObjectID?

疯子

我尝试通过查找特定的“ _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 ...
亚历山大·克韦托耶维奇(Aleksandar Cvetojevic)

只需将代码的第一行替换为

const { MongoClient, ObjectID } = require('mongodb');

您需要导入ObjectID类才能使用它。您可以在此处查看所有导出的列表:https : //github.com/mongodb/node-mongodb-native/blob/master/index.js

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章