你是对的,strict: true 应该这样做,但没有。
Mongoose 没有提及它接受的选项,尽管通常它采用底层 mongo 客户端使用的选项。
但它确实在documentation 中提到它会丢失集合:
检索一个集合,如果没有缓存则创建它。
我查看了repo,collection 方法总是会丢失集合
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];
};
mongo-client collection 确实采用了严格的参数。
您可以通过mongoose.connection.client.db()访问它
更新
你可以这样称呼它:
mongoose.connection.client.db().collection(teamName, {strict: true}, function (error, collection) {
console.log('error', error);
console.log('collection', collection);
})
示例
>
> 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
}