I'm getting a result (the object) back from a mongoose query and want to replace/remove some keys, before I stringify the object and send it to the client.
When I console.log the object, everything is nice (all the keys are listed, nothing more). When I do a for..in on the object, hidden fields popup out of nowhere (and the keys of interest, don't). They make sense - they belong to mongoose - but I don't want them. Same thing happens, when using Object.keys or Object.getOwnPropertyNames on the Object - hidden fields popup, none useful.
So I wanted to inspect the element with util.inspect(obj,true,null,true) and log the result to console. The result on the console is the same, as if I'd console.logged the object directly without the inspection.
Now, two questions;
//EDIT
OK, I got it. After some investigation, I realized, that the mongoose object proxies its properties and has a toJSON function, which explains why the console.logs were in the expected output structure. The solution is to use Mongoose own toObject method;
mongooseObj.toObject({ getters: true, virtuals: false })
This way, I can iterate over Object.getOwnPropertyNames and replace/remove keys I don't want the client to know about!
I'm going to guess that you're looking at the Document object returned by a mongoose query when you really just want to see the data. If my guess is correct, you'll probably want something like this:
Model.findOne({ name: 'john' }, function (err, doc) {
var data = doc.toObject();
// do whatever you need to with data
delete data.age;
delete data.weight;
data.isAwesome = true;
// now stringify the data and do something with it
callback(JSON.stringify(data));
});
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