Question

I get this strange behavior. Here's the thing: I make a database query and want to delete an element of the json returned by the query. So this doesn't seem to work (i.e. the element is not deleted),

var user=json;
delete user.element;

while this works

var user={element:json.element,blement:'stuff'}
delete user.element;
Was it helpful?

Solution

I think what you are referring to as JSON is actually a Mongoose document object given the tags you added to your question. Since that object is attached to it's "schema", you may have rules in there such as a "required" field or such that are interfering with the operation you are trying to do.

In order to get a raw form of the Object back, simply use the .toObject() method on the document result:

Model.findOne({ _id: id}, function(err,doc) {

    var raw = doc.toObject();
    delete raw.element;

    console.log( raw );

});

Of course you can always just omit the field from being returned in the query result with the basic form provided by .select():

Model.findOne({ _id: id}, '-element', function(err,doc) {

    console.log( doc );

});

Either form would remove that particular field from the response, but if you possibly want more control over the result than what can be provided by the field projection from .select() then use the .toObject() form and manipulate just as a plain JavaScript object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top