Kedarisetti Prasanth
Kedarisetti Prasanth

Reputation: 11

aggregation lookup by unwind is not working in mongodb

Actually, I'm having two schemas named Users and Courses. I stored all the users id that are mapped to course. Now i want to access all the user data based on user id which is stored in the courses table using aggregate, lookup and unwind. So, please help to fetch all the users data into the courses table.

I wrote the below in the Courses Controller

   const aggr = Course.aggregate([
        {
            $unwind:"$mapped_to"
        },
        {
            $lookup:{
                from:'users',
                localField:"mapped_to",
                foreignField:"_id",
                as:"result"
            }
        },
        {
            $group:{
                _id:"$_id",
                arrayField:{$push:"$mapped_to"},
                result:{$first:"$result"}
            }
        }

       ]).then((res)=>{
            console.log(res)
       })

Here is the Courses Schema of some fields

const mongoose = require('mongoose');

const schema = mongoose.Schema;
const Course = new schema({
tag:{
        type:String,
        //required:true,
        minlength:2,
        maxlength:20
    },
   ** mapped_to:{
        type:Array,
        required:true,
    },**
    added_date:{
        type:String,
        required:true,
        minlength:2,
        maxlength:500
    }
}

Here is the Users Schema

const mongoose = require('mongoose');

const schema = mongoose.Schema;
const User = new schema({
    first_name: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 50
    },
    last_name: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 50
    },
    email: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 255,
        unique: true
    }
}

Upvotes: 1

Views: 20

Answers (0)

Related Questions