Search code examples
node.jsmongoosemongoose-populate

How to populate each entry of an array of ObjectIDS?


I'm populating an array of ObjectIds. Where am I going wrong?

I tried to reference this but couldn't find the solution to my problem. Mongoose - accessing nested object with .populate

The code doing .populate:

router.get("/event", (req, res) => {
  Client.findById(req.params.client_id)
  .populate("EventsNotifications")
    .then(foundClient => {
      res.json(foundClient.eventsNotifications);
    })
    .catch(err => {
      console.log(`error from get event notifications`);
      res.json(err);
    });
});

The eventsNotifications schema:

const mongoose = require('mongoose'),
      Schema   = mongoose.Schema;

const eventNotificationSchema = new Schema({

    notification: {
        type: String,
    },
    read: {
        type: Boolean,
        default: false,
    }

}, {timestamps: true});

module.exports = mongoose.model("EventNotification",eventNotificationSchema);

The clientSchema:

const mongoose = require("mongoose"),
  Schema = mongoose.Schema,
  ObjectId = Schema.Types.ObjectId;

var validatePhone = function(contact) {
  var re = /^\d{10}$/;
  return contact == null || re.test(contact);
};

const clientSchema = new Schema({
  firstName: {
    type: String,
    required: true,
    minlength: 2
  },
  lastName: {
    type: String,
    required: false,
    minlength: 2
  },
  email: {
    type: String,
    required: true,
    match: [
      /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
      "Please fill a valid email address"
    ]
  },
  contact: {
    type: Number,
    required: true,
    validate: [validatePhone, "Please fill a valid phone number"]
  },
  eventsNotifications: [
    {
      type: ObjectId,
      ref: "EventNotification"
    }
  ]
});

module.exports = mongoose.model("Client", clientSchema);

I am expecting an array of all the eventsNotifications :

[{
"_id":"5d3c8d54126b9354988faf27",
"notification":"abdefgh",
"read":true
},
{"_id":"5d3c8d54126b9354988faf23",
"notification":"abdefgh",
"read":true
}
]

But I am getting an empty array if i try to console.log(foundClient.eventsNotifications[0].notification), it means eventsNotifications array is not being populated.

In fact, I don't even want to do .notification, .read, etc things on the keys, I want to return the whole array of objects.


Solution

  • In .populate function .populate("EventsNotifications"), the name of the field that contains ObjectId has to be mentioned.

    So, I just changed it to .populate("eventsNotifications") and it worked.