Search code examples
node.jsmongodbexpressmongoosemongoose-populate

Mongoose Populate does nothing


I'm new to Node.js and particularly Mongoose. I'm learning through tutorials. I think I wrote a good and simple code to display Users and their Buildings but populate() function simply display the _id of the Object :

My models :

(...) // omitted code

var userSchema = new Schema({
  login: {
    type: String,
    required: 'Login is required', 
    unique: true,
    index: true,
    uniqueCaseInsensitive: true
  },
    (...) // omitted code
  ,
  building: {
    type: Schema.Types.ObjectId,
    ref: 'Building'
  }
  createdAt: {
    type: Date,
    default: Date.now
  }
});

var buildingSchema = new Schema({
  address: {
    type: addressSchema,
    index: true,
    unique: true
  },
  planPath: String,
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Building', buildingSchema);
module.exports = mongoose.model('User', userSchema);

My routes :

  app.route('/api/v1/users/:userId')
    .get(parkingshare.readUser);

  app.route('/api/v1/buildings/:buildingId')
    .get(parkingshare.readBuilding);

My controllers :

exports.readUser = function(req, res) {
  user.findById(req.params.userId, function(err, user) {
    if (err)
      res.send(err);
    res.json(user.populate('building'));
  });
};

exports.readBuilding = function(req, res) {
  building.findById(req.params.buildingId, function(err, building) {
    if (err)
      res.send(err);
    res.json(building);
  });
};

I inserted data with theses commands :

curl --header "Content-Type: application/json"   --request POST   --data '{"address" : {"number":"01", "street":"test", "postCode":"01010", "city":"test"}, "planPath":""}' http://127.0.0.1:3001/api/v1/buildings

Result :

{
    "_id": "6027c85fce48810533194d08",
    "address": {
        "number": 1,
        "street": "test",
        "postCode": "01010",
        "city": "test"
    },
    "planPath": "",
    "createdAt": "2021-02-13T12:38:55.677Z",
    "__v": 0
}
curl --header "Content-Type: application/json"   --request POST   --data '{"login":"admin","password":"admin","lastName":"","firstName":"test","building": {"_id": "6027c85fce48810533194d08"},"parkLocations":[]}'   http://127.0.0.1:3001/api/v1/users

Result :

{
    "_id": "6027cab9ce48810533194d0f",
    "login": "admin",
    "password": "admin",
    "lastName": "",
    "firstName": "test",
    "building": "6027c85fce48810533194d08",
    "parkLocations": [],
    "buildingAdmin": true,
    "superAdmin": true,
    "createdAt": "2021-02-13T12:42:40.908Z",
    "__v": 0
}

Now when i try to get the user via the readUser method which has populate('building') through my browser :

json result

Why does populate() not working here ? I'm confused.


Solution

  • just try:

    exports.readUser = async function (req, res) {
      try {
        let result = await user.findById(req.params.userId).populate("building");
        res.json({ result });
      } catch (err) {
        res.send(err);
      }
    };
    

    or

    exports.readUser = function(req, res) {
        user.findById(req.params.userId).populate('building').exec(function (err, result) {
            if (err)  res.send(err);
            res.json({ result });
          })
    }