1

I am probably overlooking the most simple solution but I've tried anything I could come up with or find on the internet.

I'm trying to add a property to my JSON object which I need in my output. But whatever I try to add the property, it doesn't show up in my object. I verified that the 'doc' variable is an actual object.

No console errors. Console.log() shows the contents of 'doc' object and nothing more.

Anyone knows what is going on?

Blog.findOne({'slug': req.params.slug}, function(err, doc) {

  if (!err){

    if(_.isEmpty(doc)) { res.status(404).json({ response: "Nothing found here." }); } else {

      var blogPost = doc;
      blogPost.someProperty = 'test';
      console.log(blogPost); // doesn't contain new property

      res.status(200).json( { response: blogPost });

     }

   } else { throw err; }

 });

Output of blogPost/doc

{
  "response": {
    "_id": "55e31854823389ec1f5506fc",
    "title": "A sample post.",
    "slug": "a-sample-post2",
    "body": "Hello world. This is a sample post. \n\nThis should be a new paragraph.",
    "__v": 0,
    "date": "2015-08-30T14:51:00.836Z"
  }
}

A simple test like this in the browser does work. So I am really confused why it doesn't work in my NodeJS application. Something to do with callbacks/async or something?

var test = {}; 
test.prop = "test"; 
console.log(test);
Object {prop: "test"}
Jesse
  • 544
  • 5
  • 24
  • Any console errors? does it contain any properties at all? – Amit Aug 30 '15 at 22:40
  • @Amit no console errors and yes it contains what the original 'doc' contains, but nothing more. – Jesse Aug 30 '15 at 22:41
  • 1
    I wonder if the objects's internal [[Extensible]] attribute is set to false – Matthew Vita Aug 30 '15 at 22:42
  • @MatthewVita - that was my next direction... :-). it probably IS. Jesse, wrap your `doc` with a new, simple object, and set the property(es) there: `var blogPost = {doc: doc, someProperty = 'test'};` – Amit Aug 30 '15 at 22:44
  • @MatthewVita Object.isExtensible(blogPost) = true (same for doc) I'll post output of the doc, second! – Jesse Aug 30 '15 at 22:46
  • @Juhana I'll give it a try! Thanks – Jesse Aug 30 '15 at 22:50

1 Answers1

1

You should use lean function if you want to get result as object.

You could even reformat your code a bit to get rid of level of indentation.

Blog.findOne({'slug': req.params.slug}).lean().exec(function(err, doc) {

    if (err){
      throw err;
    }

    if(_.isEmpty(doc)) { 
       res.status(404).json({ response: "Nothing found here." }); 
       return;
    }

    // else is not required
    var blogPost = doc;
    blogPost.someProperty = 'test';

    res.status(200).json( { response: blogPost });
 });
Subash
  • 7,098
  • 7
  • 44
  • 70