【问题标题】:Mongoose Check If Collection ExistMongoose 检查集合是否存在
【发布时间】:2018-08-11 15:11:24
【问题描述】:

我正在尝试将 800 个对象插入到 mongodb 中,并且我正在尝试防止一次又一次地插入相同的元素。我会检查集合是否存在,不要插入,否则插入 800 个对象。

mongoose.connect('mongodb://localhost/testDB', function(err,db){
  if(err){
    console.log(err)
  }
  db.listCollections().toArray(function(err, collections){
    console.log(collections);
  });
});

但是控制台抛出错误并显示:

(node:24452) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: db.listCollections is not a function
(node:24452) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我现在卡住了,谢谢。

【问题讨论】:

  • 看看this是否适合你。
  • TypeError: 无法读取未定义的属性“listCollections”
  • 看起来你的连接对象数据库没有定义
  • 查看this 是否与您的问题有关。您必须通过传递您的数据库名称从数据库中获取数据库对象。如果用于登录数据库,则 url 中的 db。

标签: javascript node.js mongodb mongoose


【解决方案1】:

client.db 上有listCollections 功能,你试过吗?

mongoose.connect('mongodb://localhost/testDB', function(err, client) {
    if(err) {
        console.log(err)
    }

    client.db.listCollections().toArray(function(err, collections) {
        console.log(collections);
    });
});

【讨论】:

    猜你喜欢
    • 2012-11-06
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-12-22
    • 2010-12-16
    相关资源
    最近更新 更多