Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Properties in a forEach Loop in Mongoose

lets say each post in my posts array has two properties name and number. so its something like

var posts = [{name:"hey", number: 1}, {name:"foo", number:"2"}]

Javascript allows me to change these properties in foreach loop like this:

posts.forEach(function(post){
    post.name = "bar"
});

and my array becomes:

var posts = [{name:"bar", number: 1}, {name:"bar", number:"2"}]

but it doesnt allow me add a new property like:

posts.forEach(function(post){
    post.adress = "bar"
});

my object stays the same. Is there a way to add properties in a foreach loop in javascipt

edit:

this is happening using mongoose inside a callback..

  Post.pagination(options, function(err, posts) {
    if (err) console.log(err)
    posts.forEach(function(post){
      post.votetype = 1;
    });
    console.log(posts);
    res.send({ posts : posts  })
  })

after this votetype property is not added

like image 293
s_curry_s Avatar asked Jul 31 '13 01:07

s_curry_s


People also ask

Can I break in forEach?

From the official MDN docs: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Does forEach require return?

The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself.

Does forEach work on objects?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object. keys() , Object. values() , or Object.

What is the function of forEach ()?

The forEach() method executes a provided function once for each array element.


1 Answers

The problem is that data returned from Mongoose is immutable. The code below is untested but should give you a hint on how to make the data mutable and modify it.

The key point is calling toObject() on the Mongoose document object you wish to modify.

Post.pagination(options, function(err, posts) {
  if (err) console.log(err);

  var resultPosts = posts.map(function(post) {
    var tmpPost = post.toObject();

    // Add properties...
    tmpPost.votetype = 1;

    return tmpPost;
  });

  console.log(resultPosts);
  res.send({ posts : resultPosts  });
});
like image 154
whirlwin Avatar answered Oct 29 '22 17:10

whirlwin