Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to inspect/iterate over an object in node?

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;

  1. How do I correctly inspect an object, so that I actually get internal/hidden information about the object?
  2. How can I iterate over the object and only get the fields? (yes, I am doing the hasOwnProperty check within the for..in loop)

//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!

like image 488
japrescott Avatar asked Oct 09 '22 11:10

japrescott


1 Answers

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));
});
like image 75
abe Avatar answered Oct 14 '22 13:10

abe