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.
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.
Following JS-specific properties are skipped by JSON.stringify method. Function properties (methods). Symbolic properties. Properties that store undefined.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With