Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate in 3 collection in mongoDB with Mongoose

I have three collections such as User, Program, and `Agenda. Those models as follows.

User Model

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
    name: {type:String},
    email: {type:String}
},{timestamps:true
}
);

module.exports = mongoose.model('User', UserSchema);

Program Model

const mongoose = require('mongoose');

const NoteSchema = mongoose.Schema({
    name: {type:String},
    timefrom: {type:Date},
    timeto: {type:Date},
    status: {type:String},
    venue: {type:String},
    timetype: {type:Number},
    userid:{type:mongoose.Schema.Types.ObjectId,ref : 'User', required: true},
    logo :{type:String,default: 'programe'}
},{timestamps:true
});

module.exports = mongoose.model('Program', NoteSchema);

Agenda Model

const mongoose = require('mongoose');

const AgendaSchema = mongoose.Schema({
    name: {type:String},
    timefrom: {type:Date},
    timeto: {type:Date},
    status: {type:String},
    proorder: {type:String},
    proid:{type:mongoose.Schema.Types.ObjectId,ref : 'Program', required: true}
},
{timestamps:true}
);

module.exports = mongoose.model('Agenda', AgendaSchema);

Now I only get agenda and program data only.

Agenda Controller

// Retrieve and return all agenda from the database.
exports.findAll = (req, res) => {

    Agenda.find()
    .populate('proid')
    //.populate('userid')

    .then(agendas => {
        res.send(agendas);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occurred while retrieving agenda."
        });
    });
};

When I go to this URL and GET method I want to populate agenda document(done), related program document(done) and related user document(this I want)?

The wanted query as like this

SELECT * 
FROM users, programs, agendas
WHERE agendas.proid = programs.id AND programs.userid = users.id
like image 959
S.Sakthybaalan Avatar asked Aug 07 '18 10:08

S.Sakthybaalan


People also ask

How does populate work in Mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

Can we use populate in aggregate MongoDB?

To use populate and aggregate in same statement with MongoDB and Node. js, we can call populate with the aggregation result returned from aggergate . to call aggregate to return a promise with the aggregation result.

Can Mongoose connect to multiple databases?

Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.

What is third parameter in Mongoose model?

ref is part of Mongoose's support for reference population. The third parameter to mongoose. model is an explicit collection name.


1 Answers

You can either use $lookup aggregation

Agenda.aggregate([
  { "$lookup": {
    "from": Program.collection.name,
    "let": { "proid": "$proid" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$_id", "$$proid" ] } } },
      { "$lookup": {
        "from": User.collection.name,
        "let": { "userid": "$userid" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$userid" ] } } },
        ],
        "as": "userid"
      }},
      { "$unwind": "$userid" }
    ],
    "as": "proid"
  }},
  { "$unwind": "$proid" }
])

Or with populate

Agenda.find()
  .populate([{ path: 'proid', populate: { path: 'userid' }}])

Both will give you the same result

like image 112
Ashh Avatar answered Oct 05 '22 05:10

Ashh