Home > Net >  mongoose - I want to find a documents that contain a nested reference?
mongoose - I want to find a documents that contain a nested reference?

Time:11-04

I'm new to mongoose and MongoDB and I have a question, I want to find documents that contain a reference of reference.

I have 2 models like this:

1: Posts with ref to categories:

const postsSchema = new Schema({
    post_title: {
        type: String,
        required:true
    },
    post_categories: [{
        type: Schema.Types.ObjectId, 
        ref: 'categories',
        required:true
    }],
});

2: categories with ref to categories

const categoriesSchema = new Schema({
    categoryName: {
        type: String,
        required: true
    },

    categoryParent: {
        type: Schema.Types.ObjectId,
        ref: 'categoriesSchema',
      }
});

I want to find all posts which have a category parent for example (news), I try this:

Posts.find({'post_categories.categoryParent.categoryName': 'news'});

but I got an empty array []. Is there a way to find documents that contain a reference of reference?

CodePudding user response:

I found the solution by using MongoDB aggregate, I don't know if it optimal solution, but it solved my issue:

var allnews = await postsDB.aggregate([
    {$unwind: "$post_categories"},
    {$lookup: {
      from: "categories",
      localField: "post_categories",
      foreignField: "_id",
      as: "newCategoryName"
    }},
    { $unwind: "$newCategoryName"
    },
    {$lookup: {
      from: "categories",
      localField: "newCategoryName.categoryParent",
      foreignField: "_id",
      as: "newCategoryParent"
    }},
    { $unwind: "$newCategoryParent"
    },
    {
      $match: {
        "newCategoryParent.categoryName": "News"
    }}
  ]);

Now I have all posts which have the parent category is "News" whatever child category is

  • Related