简体   繁体   English

基于对象属性查询Mongoose文档

[英]Query Mongoose Documents Based on Object Properties

I have the following Mongoose Schema: 我有以下Mongoose Schema:

var UserSchema = new Schema({
  name: String,
  age: Number,
  ...
  tags: [{
    text: String,
    ...
  }]
});

and the following array: 和以下数组:

var tagTexts = ['tall', 'small', 'green', 'blue'];

I would like to retrieve all user documents that contain at least one tag with a text property found within tagTexts. 我想检索包含至少一个带有tagTexts中找到的text属性的标签的所有用户文档。

For example, if I had the following users and tagTexts array 例如,如果我有以下用户和tagTexts数组

[{
  name: 'Bob',
  age: 17,
  ...
  tags: [{
    text: 'small',
    ...
  }]
}, {
  name: 'Bill',
  age: 29,
  ...
  tags: [{
    text: 'dandelion',
    ...
  }, {
    text: 'oak',
    ...
  }]
}]

var tagTexts = ['tall', 'small', 'green', 'blue'];

then Bob would be retrieved, but not Bill. 然后鲍勃会被检索,但不是比尔。

You can use $in to match against an array of values, and dot notation to target the text field within each element of the tags array. 您可以使用$in来匹配值数组,并使用点符号来定位tags数组的每个元素中的text字段。 Any match will cause a doc to be included in the results. 任何匹配都会导致文档包含在结果中。

var tagTexts = ['tall', 'small', 'green', 'blue'];
User.find({'tags.text': {$in: tagTexts}}, function(err, users) {...});

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

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