简体   繁体   English

mongoose 有没有办法在找不到时不创建集合?

[英]Is there a way in mongoose to not create a collection if not found?

We are creating a discord bot for task management based on teams.我们正在创建一个 discord 机器人,用于基于团队的任务管理。 We're using a collection as a team.我们正在使用一个集合作为一个团队。 In code to find a team and add tasks to it we use: const Team = await mongoose.connection.collection(teamName, {strict: true});在查找团队并向其添加任务的代码中,我们使用: const Team = await mongoose.connection.collection(teamName, {strict: true}); and strict is supposed to make it so that the collection isn't created when it's not found but instead this happens:并且strict应该做到这一点,以便在找不到集合时不会创建集合,而是会发生这种情况:

即使团队不存在也创建任务

I've tried with no luck as the mongoose has no documentation on the options and everything I've tried doesn't work.我试过没有运气,因为 mongoose 没有关于选项的文档,而且我尝试过的所有东西都不起作用。

How do I make mongoose.connection.collection(teamName) return an error if teamName isn't a collection name/isn't found?如果teamName不是集合名称/未找到,如何使mongoose.connection.collection(teamName)返回错误?

You are right, strict: true should do it, but doesn't.你是对的, strict: true应该这样做,但没有。 Mongoose doesn't mention the options it accepts, though usually it takes the ones used by the underlying mongo client. Mongoose 没有提及它接受的选项,尽管通常它采用底层 mongo 客户端使用的选项。 But it does mention in the documentation that it makes missing collections:但它确实在文档中提到它缺少 collections:

Retrieves a collection, creating it if not cached.检索一个集合,如果没有缓存则创建它。

I looked into the repo , and the collection method always makes a missing collection我查看了repocollection方法总是会丢失一个集合

Connection.prototype.collection = function(name, options) { const defaultOptions = { autoIndex: this.config.autoIndex?= null. this.config:autoIndex. >this.base.options,autoIndex: autoCreate. this.config?autoCreate.= null. this:config.autoCreate. >this.base;options.autoCreate }, options = Object,assign({}? defaultOptions. options: utils;clone(options). {}). options;$wasForceClosed = this.$wasForceClosed. if (,(name in this,collections)) { this;collections[name] = new Collection(name. this; options); } return this.collections[name]; };

The mongo-client collection does take a strict parameter. mongo-client 集合确实采用了严格的参数。 You can access it via mongoose.connection.client您可以通过mongoose.connection.client访问它

Update更新

Here is how you can call it:以下是你如何称呼它:

mongoose.connection.client.db().collection(teamName, {strict: true}, function (error, collection) {
  console.log('error', error);
  console.log('collection', collection);
})

Example例子

>
> mongoose.connection.client.db().collection('nonExistantCollectionName', {strict: true}, function () { console.log(arguments) })
undefined
> [Arguments] {
  '0': MongoError: Collection nonExistantCollectionName does not exist. Currently in strict mode.
      at Function.create (./node_modules/mongodb/lib/core/error.js:57:12)
      at toError (./node_modules/mongodb/lib/utils.js:130:22)
      at ./node_modules/mongodb/lib/db.js:482:9
      at ./node_modules/mongodb/lib/utils.js:704:5
      at handleCallback (./node_modules/mongodb/lib/utils.js:109:55)
      at ./node_modules/mongodb/lib/cursor.js:840:66
      at ./node_modules/mongodb/lib/utils.js:704:5
      at ./node_modules/mongodb/lib/cursor.js:925:9
      at CommandCursor._endSession (./node_modules/mongodb/lib/core/cursor.js:397:7)
      at ./node_modules/mongodb/lib/cursor.js:923:12
      at maybePromise (./node_modules/mongodb/lib/utils.js:692:3)
      at CommandCursor.close (./node_modules/mongodb/lib/cursor.js:916:12)
      at ./node_modules/mongodb/lib/cursor.js:840:27
      at ./node_modules/mongodb/lib/core/cursor.js:739:9
      at handleCallback (./node_modules/mongodb/lib/core/cursor.js:32:5)
      at ./node_modules/mongodb/lib/core/cursor.js:683:38
      at _setCursorNotifiedImpl (./node_modules/mongodb/lib/core/cursor.js:696:10)
      at setCursorNotified (./node_modules/mongodb/lib/core/cursor.js:683:3)
      at done (./node_modules/mongodb/lib/core/cursor.js:458:16)
      at queryCallback (./node_modules/mongodb/lib/core/cursor.js:503:20)
      at ./node_modules/mongodb/lib/core/cursor.js:548:9
      at ./node_modules/mongodb/lib/utils.js:704:5
      at executeCallback (./node_modules/mongodb/lib/operations/execute_operation.js:65:7)
      at callbackWithRetry (./node_modules/mongodb/lib/operations/execute_operation.js:112:14)
      at ./node_modules/mongodb/lib/operations/command_v2.js:102:9
      at ./node_modules/mongodb/lib/core/connection/pool.js:405:18
      at processTicksAndRejections (internal/process/task_queues.js:79:11) {
    driver: true
  },
  '1': null
}


You can use this code to check if a collection exists or not in a specific database - and then perform actions as needed.您可以使用此代码检查特定数据库中是否存在集合 - 然后根据需要执行操作。

const mongoose = require('mongoose');
const uri = 'mongodb://127.0.0.1:27017/';
const opts = { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
    dbName: 'test' 
};

(async () => {
    const conn = await mongoose.createConnection(uri, opts);
    let collNames = await conn.db.listCollections().toArray();
    collNames = collNames.map(e => e.name);
    console.log(collNames);
    console.log(collNames.includes('existing_coll'));       // true
    console.log(collNames.includes('non_existing_coll'));   // false
    await conn.close();
})(uri, opts);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM