Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js and JSON.stringify missing some values/parameters from object

Maybe I don't understand javascript/coffee script as well as I thought but when I do this:

that.thing = thing
that.thing.title = "some title"
console.log(that.thing.title)
console.log(JSON.stringify(that.thing)

I get output:

some title

{"creation_date":"2011-09-09T00:40:03.742Z","_id":"4e6960638ec80519a0000013"}

The problem is I seem to lose the title property when I do the stringify (and later on when the function exists I seem to be having other interesting problems which I assume have to do with 'that' and this nested within multiple fxn calls).

(I had to do an ugly solution for now where I do that.thing = {} to solve my problem. Other problems I had to solve before included node.js + async + mongoose.find and this is all inside async.findEach)

When I do

console.log(that.thing.toJSON) 

I get:

function () { return this.toObject(); }

Thanks.

like image 893
user885355 Avatar asked Sep 09 '11 20:09

user885355


People also ask

Does JSON Stringify work on objects?

JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans. Anything else will be ignored or throw errors.

What is specific properties are skipped by JSON Stringify method?

Following JS-specific properties are skipped by JSON.stringify method. Function properties (methods). Symbolic properties. Properties that store undefined.

How do I Stringify a JSON object in node JS?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.


1 Answers

This is because Model.find() is returning a MongooseDocument. If you want a plain JavaScript object, which you can add properties to, you need to specify the "lean" option:

Model.find().lean().exec(function (err, thing) {
    thing.title = "some title";
    console.log(JSON.stringify(thing));
});

This will work fine, provided you don't need to save the thing object again (as this is not a MongooseDocument, no getters and setters are applied).

like image 122
Lee Crossley Avatar answered Oct 21 '22 12:10

Lee Crossley