如何在没有ID的ref对象内查找文档?

时间:2019-04-22 13:13:51

标签: node.js mongodb mongoose

我在mongodb中有两个文档:

export const Category = mongoose.model('Category', new mongoose.Schema({
    name: { type: String },
}));

export const SubCategory = mongoose.model('SubCategory', new mongoose.Schema({
    name: { type: String },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
}));

如何查找按名称匹配“类别”的所有子类别?

我尝试了很多方法,但是我总是得到null或错误...

var name = '...';

SubCategory.find({ category: { name } });

SubCategory.find({ category: { name } }).populate('category');

2 个答案:

答案 0 :(得分:0)

您可以对它使用聚合。请阅读此文档https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

答案 1 :(得分:0)

注意:-此答案基于您的收集和输入的数据。这不是完美的方法,但这将最好地帮助您从该答案中找到逻辑。 :-)

   //collection 1 schema
    const collection1Schema = new Schema({
     user_id: {
      type: String,
      required: true
     },
     status: {
      type: String
     }
    });
    mongoose.model('Collection1', collection1Schema);
    //collection 2 schema
    const collection2Schema = new Schema({
     user_id: {
      type: Schema.Types.ObjectId,
      ref: 'user_id'
     },
     item: {
      type: String
     }
    });
    mongoose.model('Collection2', collection2Schema);
    //find data from collection2
    Collection2.find()
     .populate('user_id')
     .exec(function(err, foundDocuments) {
      if (error) {
       console.error(err);
      } else {
       console.log(foundDocuments);
      }
     });

有关更多信息:-Mongoose populate