【问题标题】:Dynamic query in mongo and NodeJs asking for fields of documents embedded?mongo 和 NodeJs 中的动态查询要求嵌入文档的字段?
【发布时间】:2019-11-14 23:13:58
【问题描述】:

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

在我的应用程序中,我的发布模式嵌入了 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 方法我构建查询,从对象 filter 获取所有用户输入值,我还有 query 对象,我在其中推送不同的条件并将其与 $and 一起使用/p>

  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.specie 等于 cat 的出版物??
  • @AliElkhateeb 是的,还有查询的其余部分,例如发布状态以及我的应用程序具有的其他字段

标签: javascript node.js mongodb mongoose


【解决方案1】:

你可以去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'的Publications

【讨论】:

  • 这会带来所有出版物,但不会为那些不是“猫”的出版物填充“宠物”字段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多