Home > Net >  How to get model data from nested object
How to get model data from nested object

Time:12-03

little bit stuck with mongoose. I want to get all users projects where he's added. Tried few options, but in all of them I receive an empty array. So the main question is it possible somehow to find all project by filtering/finding the Project model?

This is how looks my default response to understand what I'm looking for:

{
            "_id": "61a8bc4e8e24f10ac7a7288d",
            "name": "Random project",
            "description": "Random project desc",
            "maxWorkingEmployees": 5,
            "status": "Paused",
            "createdBy": {
                "_id": "61a66578f2dabf7555bcf4ab",
                "email": "[email protected]",
                "role": "Owner"
            },
            "currentlyWorkingEmployees": [
                {
                    "username": "Ema",
                    "role": "Employee",
                    "_id": "61a8e0423140ecce769dc971"
                }
            ],
            "createdAt": "2021-12-02T12:30:06.461Z",
            "updatedAt": "2021-12-02T15:11:51.361Z",
            "__v": 0
        }

Project model:

const mongoose = require('mongoose');

const SingleUserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  role: {
    type: String,
    required: true,
  },
});

const ProjectSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, 'Provide project name'],
      minlength: 5,
    },
    description: {
      type: String,
      required: [true, 'Provide description about the project'],
    },
    maxWorkingEmployees: {
      type: Number,
      required: [
        true,
        'Provide maximum number of employees working on this project',
      ],
    },
    currentlyWorkingEmployees: [SingleUserSchema],
    status: {
      type: String,
      enum: ['Pending', 'In progress', 'Paused', 'Delayed', 'Completed'],
      default: 'Pending',
    },
    createdBy: {
      type: mongoose.Schema.ObjectId,
      ref: 'User',
      required: true,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model('Project', ProjectSchema);

Here's my controller and my first try:

const getMyProjects = async (req, res) => {
  const userId = req.user.userId;
  const projects = await Project.find({
    currentlyWorkingEmployees: { _id: userId },
  });
  res.json({projects});
};

Second shot after reading some articles

const getMyProjects = async (req, res) => {
  const userId = req.user.userId;

  const projects = await Project.aggregate([
    {
      $match: {
        currentlyWorkingEmployees: { _id: userId },
      },
    },
  ]);
};

CodePudding user response:

As I said in the comment you can do it accessing to the internal object of the schema with an string accessing to it child object.

Project.find({'currentlyWorkingEmployees._id': userId})
  • Related