Question

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!

Was it helpful?

Solution

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));
});

OTHER TIPS

Also if you want to access a certain field from a Document you can take a look at:

Document#get

// path
doc.get('age') // 47

// dynamic casting to a string
doc.get('age', String) // "47"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top