2

JavaScript #mongoDB #express #nodejs

I have an array of objects that I receive from a mongoDB. After receiving the array of "areas" I want to add an key to each object in the array. (The added key will be the localized fromat of a date value that will later be used when rendering the HTML page.)

// we are inside a express controller for a webapp here
var moment = require('moment');

exports.getAllAreas = function(req, res) {
  AreaModel.find().sort('-updatedAt').exec(function(err, allAreas) {
    if (err) return next(err);
    console.log("area table data:\n%s", JSON.stringify(allAreas, null, '  '));
    for (var i = allAreas.length - 1; i >= 0; i--) {
      allAreas[i]['createdAt_View'] = moment(allAreas[i].createdAt).format('L');
    };
    console.log("area table data ###:\n%s", allAreas);
    res.json(allAreas);
  });
};

The data coming from mongoDB ("allAreas" array) is:

[
  {
    "_id": "56f0f7cdd99f646c99ad1e2f",
    "updatedAt": "2016-03-19T13:02:19.000Z",
    "createdAt": "2016-03-19T13:02:19.000Z",
    "description": "Very important topics",
    "title": "Another Area"
  },
  {
    "_id": "56f0f7eed99f646c99ad1e30",
    "updatedAt": "2016-03-01T13:02:19.000Z",
    "createdAt": "2016-01-19T13:02:19.000Z",
    "description": "Even more",
    "title": "Area2"
  }
]

My problem: After the for loop the allAreas array and its contents are not changed at all!

Some more sidenotes: - I use a (backward) for-loop instead of a .foreach clause, because this is faster. - "moment" is a JS library that can localize data values

Are mongoDB results somehow immutable in Javascript? Am I missing something with by-value or by-reference here? I just don't find it.


Solution (credits got to @RayonDabre)

Mongoose (the OR-mapper that I use) returns a Mongoose Document from the query. So the variable allAreas in the callback is actually a 'bigger' Javascript Object, that you cannot add properties to in this way.

When you add .lean() to the Mongoose Query Builder, then mongoose returns a plain javascript associative array, that you can add keys to.

Thanks to all stackoverflow members for helping so quickly!

Community
  • 1
  • 1
Robert
  • 1,579
  • 1
  • 21
  • 36

0 Answers0