猫鼬–查询ID引用的子文档

时间:2019-08-14 12:42:52

标签: node.js mongodb mongoose

我有2个这样连接的架构:

const Brand = new mongoose.Schema({
  _id: { type: String, required: true },
  name: {
    type: String,
    required: true,
  },
  products: [{
    type: String,
    ref: 'Product',
  }],
});

const Product = new mongoose.Schema({
  _id: { type: String, required: true },
  name: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
});

我想找到具有某些特定类型产品的品牌,因此我编写了一个查询(为简单起见,下面的代码中不包括async / await和promises)

const docs = Brand.find({ 'products.type': 'my-type-here' })
      .populate([
        {
          path: 'products',
        },
      ])
      .sort({ index: 1 })
      .exec();

这给了我0条结果,但我知道有些品牌带有产品类型。我在这里做错了什么?这与事实有关,即当我调用find方法时,产品仅由其ID引用吗?

0 个答案:

没有答案