Search code examples
mongodbexpressmongoosepopulatemongoose-populate

Model.populate() is not return document in Mongoose


I have two schema,

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create the User Schema
const UserSchema = new Schema({
    email: {
        type: String
    },
    password: {
        type: String
    }
});

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

OR

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create the Status Schema
const StatusSchema = new Schema({
    admin_id:{
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text:{
        type: String
    },
});

module.exports = Status = mongoose.model("Status", StatusSchema, "Status");

then i use the populate in my api route:

router.get(
  "/",
  passport.authenticate("jwt", {
    session: false,
  }),
  (req, res) => {
    try {
      Status.find({}).populate('admin_id').exec(err, data=>{
        console.log(data); // return a blank array : []
        return res.sendStatus(200)
      })
    }
  } catch (error) {
      res.sendStatus(500);
    }
  }
);

When i call this route i got an empty array [] .... Any idea what i do wrong? I should mention that i have inserted records in status collection for both admin_id

Is there any onther way to do this ?


Solution

  • There is a lot of ways to do this.

    You sould use this,

    Status.find({}).then((doc) => {
      if (doc) {
        Status.populate(doc, { path: "admin_id", model: "users" }, function (
          err,
          data
        ) {
          if (err) throw err;
          console.log(data); //here is your documents with admin user
        });
      }
    });