Mongoose - find(): 搜索选项中的对象不起作用

cha*_*nie 2 javascript mongoose mongodb node.js mongodb-query

我有一个看起来像这样的猫鼬模式:

var mySchema = new mongoose.Schema({
  ...
  metadata: {
    isDeleted: {
      type: Boolean,
      default: false
    },
    ...
  }
});
Run Code Online (Sandbox Code Playgroud)

我想获取应用过滤器的mongodb数据库中的元素列表,所以我有以下对象:

var searchOptions = { metadata: { isDeleted: false } };
Run Code Online (Sandbox Code Playgroud)

在执行查询之前,始终需要将该metadata.isDeleted值设置为false,与稍后将添加的其他参数分开:

var objQuery = myModel.find(searchOptions, '-metadata');
Run Code Online (Sandbox Code Playgroud)

起初,我在架构中的对象isDeleted之外有属性metadata,并且

var searchOptions = { isDeleted: false };
Run Code Online (Sandbox Code Playgroud)

used to work perfectly. But it is since I decided to have isDeleted inside my metadata object that is not working and can't figure out why...

Bla*_*ven 6

It seems pretty likely given your use of elipsis in your schema listing that there are more properties than isDeleted under the metadata property. So your object should be:

var searchOptions = { "metadata.isDeleted": false } };
Run Code Online (Sandbox Code Playgroud)

The reason for this is that otherwise the query is looking for a document with "exactly" and "only" the properties named under the metadata key:

var searchOptions = { metadata: { isDeleted: false } };
Run Code Online (Sandbox Code Playgroud)

And when that is not the case, then of course there is no match.