JavaScript append property to object -
this question has answer here:
i overlooking simple solution i've tried come or find on internet.
i'm trying add property json object need in output. whatever try add property, doesn't show in object. verified 'doc' variable actual object.
no console errors. console.log() shows contents of 'doc' object , nothing more.
anyone knows 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. sample post. \n\nthis should new paragraph.", "__v": 0, "date": "2015-08-30t14:51:00.836z" } }
a simple test in browser work. confused why doesn't work in nodejs application. callbacks/async or something?
var test = {}; test.prop = "test"; console.log(test); object {prop: "test"}
you should use lean
function if want result object
.
you reformat code bit 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 not required var blogpost = doc; blogpost.someproperty = 'test'; res.status(200).json( { response: blogpost }); });
Comments
Post a Comment