mongo和NodeJ中的动态查询要求嵌入文档的字段?

时间:2019-11-13 00:21:52

标签: javascript node.js mongodb mongoose

我正在尝试根据用户的多个选择进行动态查询。

在我的应用程序中,我具有包含以下内容嵌入的Pet模式的发布模式:

var status = ["public", "private", "deleted"];

var publication_schema = new Schema({
  pet:{
    type: Schema.Types.ObjectId, 
    ref: "Pet"
  },
  status: {
    type: String,
    enum: status,
    default: status[0]
  }
});

module.exports = mongoose.model('Publication', publication_schema);

var pet_schema = new Schema({
  type: {
    type: String,
    require: true
  },
  createdDate: { 
    type: Date, 
    default: Date.now 
  }
});

module.exports = mongoose.model('Pet', pet_schema);

插入一个async方法,我构建查询,从对象filter获取所有用户输入值,还有一个query对象,在其中推送不同的条件并使用它$and

  let query = {};
  let contentQuery = []

  if (filter.public && !filter.private) {
    contentQuery.push({ status: { $eq: "public" } });
  } else if (filter.privada && !filter.public) {
    contentQuery.push({ status: { $eq: "private" } });
  } 

 query = { $and: contentQuery }
 try {
    const publication = await Publication.find(query).populate('pet');

  } catch (e) {
    console.log(e)
  }

问题是当我想添加更多条件时,例如:

if (filter.specie) { // for example filter.specie equals 'cat'
     contentQuery.push({ pet: { type: { $eq: filter.specie } } });
}

我得到了错误:

'Cast to ObjectId failed for value "{ type: { \'$eq\': \'cat\' } }" at path "pet" for model "Publication"',
  name: 'CastError',
  stringValue: '"{ type: { \'$eq\': \'cat\' } }"',
  kind: 'ObjectId',
  value: { type: { '$eq': 'cat' } },
  path: 'pet',
  reason: undefined,
  model: Model { Publication } }

所以。如何查询发布的字段以及发布内部的pet字段?

1 个答案:

答案 0 :(得分:0)

您可以看看Populate Query Conditions

您可以代替.populate('pet')做类似的事情

Publication.find({})
  .populate({
    path: 'pet',
    match: { specie: 'cat'},
    // You can select the fields you want from pet, or remove the select attribute to select all
    select: 'name -_id',
    // Here you could add options (e.g. limit)
    options: { limit: 5 }
  }).exec();

以上查询将为您提供pet.specie等于'cat'的所有出版物