Mongoose findOne() 和 find() 返回无效值,它们应该分别返回 null / 空列表

Posted

技术标签:

【中文标题】Mongoose findOne() 和 find() 返回无效值,它们应该分别返回 null / 空列表【英文标题】:Mongoose findOne() and find() return invalid values, when they should return null / empty list respectively 【发布时间】:2022-01-24 03:25:15 【问题描述】:

当我这样做时

const currencyFound = await Currency.findOne(some_field_that_does_not_exist_in_any_currency : value);

currencyFound 永远不会为空,它在逻辑上应该是什么时候?它似乎是从 Currencies 集合中获取的一些随机文档,即使集合中的所有文档(包括获取的文档)都没有与 findOne 过滤器中指定的字段相同的字段(some_field_that_does_not_exist_in_any_currency)。

我这样做时的类似行为

const currenciesFound = await Currency.find(some_field_that_does_not_exist_in_any_currency : value);

我期望一个空列表,但我得到了集合中的所有记录! 怎么回事?

更新 1

如果我删除 await 和 console.log 结果,这就是我得到的:

Query 
  _mongooseOptions: ,
  _transforms: [],
  _hooks: Kareem  _pres: Map(0) , _posts: Map(0)  ,
  _executionStack: null,
  mongooseCollection: Collection 
    collection: Collection  s: [Object] ,
    Promise: [Function: Promise],
    modelName: 'Currency',
    _closed: false,
    opts: 
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: [Object],
      capped: false,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    ,
    name: 'currencies',
    collectionName: 'currencies',
    conn: NativeConnection 
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: ,
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: ,
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: undefined,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _queue: [],
      _listening: false,
      _connectionString: 'mongodb://****:****/****',
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      db: [Db],
      host: '****',
      port: ****,
      name: '****'
    ,
    queue: [],
    buffer: false,
    emitter: EventEmitter 
      _events: [Object: null prototype] ,
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    
  ,
  model: Model  Currency ,
  schema: Schema 
    obj:  name: [Object], symbol: [Object] ,
    paths: 
      name: [SchemaString],
      symbol: [SchemaString],
      _id: [ObjectId],
      updatedAt: [SchemaDate],
      createdAt: [SchemaDate],
      __v: [SchemaNumber]
    ,
    aliases: ,
    subpaths: ,
    virtuals:  id: [VirtualType] ,
    singleNestedPaths: ,
    nested: ,
    inherits: ,
    callQueue: [],
    _indexes: [],
    methods:  initializeTimestamps: [Function (anonymous)] ,
    methodOptions: ,
    statics: ,
    tree: 
      name: [Object],
      symbol: [Object],
      _id: [Object],
      updatedAt: [Function: Date],
      createdAt: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    ,
    query: ,
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
    '$id': 2,
    mapPaths: [],
    s:  hooks: [Kareem] ,
    _userProvidedOptions:  timestamps: true ,
    options: 
      timestamps: true,
      typeKey: 'type',
      id: true,
      _id: true,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: true,
      strict: true,
      pluralization: true
    ,
    '$timestamps':  createdAt: 'createdAt', updatedAt: 'updatedAt' ,
    '$globalPluginsApplied': true,
    _requiredpaths: [ 'symbol', 'name' ]
  ,
  op: 'findOne',
  options: ,
  _conditions:  some_field_that_does_not_exist_in_any_currency: 'GBP' ,
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection 
    collection: Collection 
      collection: [Collection],
      Promise: [Function: Promise],
      modelName: 'Currency',
      _closed: false,
      opts: [Object],
      name: 'currencies',
      collectionName: 'currencies',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    ,
    collectionName: 'currencies'
  ,
  _traceFunction: undefined,
  '$useProjection': true


【问题讨论】:

如果console.log Ticket.findOne( ... ) 没有 await,你会得到什么? @MontgomeryWatts 将结果添加到帖子中。谢谢 【参考方案1】:

Mongoose 有一个名为 strictQuery 的模式选项。如果此值设置为true,则过滤器中不属于架构的字段将从过滤器中删除。它的默认值等于选项strict的值,默认为true

const mySchema = new Schema( field: Number ,  strict: true );
const MyModel = mongoose.model('Test', mySchema);
// Mongoose will filter out `notInSchema: 1` because `strict: true`, > meaning this query will return
// _all_ documents in the 'tests' collection
MyModel.find( notInSchema: 1 );

如果您将strictQuery 设置为false,则不存在的字段应保留为过滤器的一部分。

const mySchema = new Schema( field: Number , 
    strict: true,
    strictQuery: false // Turn off strict mode for query filters
);
const MyModel = mongoose.model('Test', mySchema);
// Mongoose will not strip out `notInSchema: 1` because `strictQuery` is false
MyModel.find( notInSchema: 1 );

【讨论】:

以上是关于Mongoose findOne() 和 find() 返回无效值,它们应该分别返回 null / 空列表的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose findOne() 和 find() 返回无效值,它们应该分别返回 null / 空列表

如何模拟像findOne()这样的mongoose查询?

NestJS TypeORM MongoDB 无法使用 find 或 FindOne 搜索存储库

节点,猫鼬“findOne”在另一个集合的“find”内的一个集合上

mongoose使用之查询篇

Mongoose find - 从查询中返回所有匹配的至少一个