1

I am new to MongoDB and trying to join two query and store result in a single model. I want to fetch client name from another collection while fetching client task.

Model:-

const mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;

const ClientTaskSchema = new mongoose.Schema({
  clientId: {
    type: Number
  },  
  taskId: {
    type: Number
  },
  clientTaskId: {
    type: Number
  },
  active: {
    type: Boolean
  }
});

module.exports = mongoose.model('ClientTask', ClientTaskSchema);

Controller:-

module.exports.getClientByTask = function(req, res) {
var query = url.parse(req.url,true).query;
ClientTask.find({taskId: query.taskId}, function(err, clientTask) {
    if (err) throw err;
    if (!clientTask) {
        res.status(200).json({ success: false, message: 'Somthing went wrong. Please contact admin.'});
    }
    else {
        res.status(200).json({ success: true, message: 'Successfull', data: clientTask});
    }
});
};

2 Answers 2

2

One option is to pass clientId as a reference:

clientId: {
 type: mongoose.Schema.Types.ObjectId, ref: 'Client / or whatever your model'
}

Then you'll be able to use Mongoose's populate method http://mongoosejs.com/docs/populate.html

ClientTask
  .find({ taskId: query.taskId })
  .populate('clientId', { name: 1 }).exec(function (err, clientTask) {
    if (!clientTask) {
      res.status(404).json({ message: 'Client task not found' })
    }
   // your logic
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can fetch aggregated data with mongodb aggregate. To Calculates aggregate values for the data in a collection:

$lookup Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the “joined” collection. The $lookup stage passes these reshaped documents to the next stage.

In your case:

Model.ClientTask.aggregate([
  {
     $lookup:
      {
          from: "client",
          localField: "_id",
          foreignField: "clientId",
          as: "clientData"
      },
  }, 
  {
    $project: {
              "name": clientData.name,   // This name will be client name from client collections
              "taskId": 1,
              "clientTaskId": 1,
              "active": 1
     }
  }
],
function (err, response) {
   console.log(err, response)
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.