2

So I am trying to add a field to a user object right before I return it and the property is not being added for some reason. Any thoughts?

returnUser = function(userRes) {
  console.log(">POST /returnuser< Returning user w/ userId: " + userRes.userId + " deviceToken: " + userRes.deviceToken);
  return Location.findOne({
    users: {
      $elemMatch: {
        user: userRes.userId
      }
    }
  }, function(error, response) {
    userRes.currentLocation = response;
    console.log(userRes);
    return res.send(userRes);
  });
};

So in the returnUser function I am searching the DB for the user's current location, adding that to the userRes object and then returning it. But when I log the userRes object it doesn't contain that property. Any issue with my code? userRes currently looks like this:

{ _id: 1,
  createTime: 1428477183281,
  deviceId: '982f24khsd',
  deviceToken: 'kjs398fskjjg5fb43ds323',
  firstName: 'Cat',
  lastName: 'Man',
  email: 'cat@mandu.com',
  __v: 0,
  users: [],
  locations: [],
  lngLat: [] }
clifgray
  • 4,313
  • 11
  • 67
  • 116

1 Answers1

6

As it turns out, that userRes object is actually a mongoose model instance returned from a mongoose query which is not mutable.

To fix this you can preferably call lean() which will give you a plain JS object instead of a full model instance.

Or if you don't have access to the query you can do something like:

mutableUserRes = JSON.parse(JSON.stringify(userRes));

Which copies the whole object but it is now a simple JS object instead of a mongoose model instance.

clifgray
  • 4,313
  • 11
  • 67
  • 116
  • 1
    I had the exact same problem today. Life-saver. Thanks! – Caio Bianchi Apr 13 '16 at 20:37
  • I was struggling from the same, however I've a confusion, how can I make my own object immutable like mongoose do ? is there any simpler way to do this – Lint Mar 20 '23 at 16:22