首页 > 解决方案 > mongoose conditional query returns unexpected doc

问题描述

Records in User Collection:

[
  {
    "__v": 0,
    "_id": "617849bc35a25323c48cdd58",
    "email": "mockEmail",
    "updatedAt": "2021-10-26T18:32:28.241Z"
  },
  {
    "__v": 0,
    "_id": "617849bc35a25323c48cdd5b",
    "email": "mockEmail2",
    "updatedAt": "2021-10-26T18:32:28.297Z"
  }
]

Code been executed:

await User.find({email:"mockEmail",tag:"mockTag"}).exec();

Result:

The first doc is returned

Expected behavior:

No document should be returned since both documents have no tag.

I tried to:

  1. Run this script on mongoplayground and got the expected result(no document found)

  2. Use $and operator even though I think this is default behavior by mongoose

await User.find({$and:[{email:"mockEmail"},{tag:"mockTag"}]}).exec();

still returned the first doc.

Package Version:

mongoose: 6.0.6

@types/node: 16.9.1

标签: node.jstypescriptmongoose

解决方案


推荐阅读