简体   繁体   English

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

[英]Dynamic query in mongo and NodeJs asking for fields of documents embedded?

I am trying to make a dynamic query based on multiple selection of the user.我正在尝试根据用户的多项选择进行动态查询。

In my application I have the Publication schema that has the Pet schema embedded as follows:在我的应用程序中,我的发布模式嵌入了 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);

Insyde an async method I build the query, getting all the user input values from the object filter , also I have the query object where I push the different criteria and use it with an $and Insyde async方法我构建了查询,从 object filter获取所有用户输入值,还有query object 在其中推送不同的条件并将其与$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)
  }

the problem is when I want to add more criteria such as follows:问题是当我想添加更多标准时:

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

I get the error:我得到错误:

'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 } }

So.所以。 How can I do to query the fields of publication and also the pet fields inside publication?如何查询出版物的字段以及出版物中的宠物字段?

You can have a look on Populate Query Conditions您可以查看填充查询条件

Instead of .populate('pet') you could do something like而不是.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();

The above query will get you all Publications with pet.specie equals to 'cat'上面的查询将为您提供所有pet.specie等于 'cat' 的出版物

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

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