Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Attribute from JavaScript Object, Returned by Mongoose's "findOneAndUpdate" Method

Tags:

I'm writing a simple server in JavaScript on Node.js, which (among other things) allows the user to manage their account (basic CRUD functionality, etc). The server is connected to a MongoDB instance, using Mongoose to manage the connection and data.

Models in Mongoose have a method called findOneAndUpdate(), which does exactly what you think it does: queries the database for the first document returned and updates said document based on parameters you passed. It then returns the new, updated document to the user. It works exactly as intended and I have no problem with it.

However, I don't want ALL of the user data returned. Specifically, I'd like to omit the _id and password fields. Since the object returned by MongoDB is a basic JavaScript object, I assumed that I'd be able to remove those attributes by calling delete object.attribute. Unfortunately, for some reason that's not working.

Here's my code that updates the user information:

case "update":   User.findOneAndUpdate({"token": header.token}, body, function(err, user) {     if (err) {       return callback(err);     } else {       delete user["_id"];       delete user["password"];       return callback(null, new SuccessEnvelope(user));     }   });   break; 

For clarity, an Envelope (in this case, a SuccessEnvelope) is a bundle of information that the client and server need in order to facilitate communication. Similar-ish to a TCP packet. Anyhow, I digress...

For example, if I wanted to update my username from "joe_bob" to "jim_bob", I'd send this to the server:

{"header": "type": "user", "method": "update", "token": "IM_A_TOKEN_GAIS_SRSLY"}, "body": {"username": "jim_bob"}}

And while the user's username is updated successfully, this is what I get in return:

{"header": {"type": "success"}, "body": {"__v": 0, "_id":"SOME_NUMERICAL_ID", "email": "[email protected]", "password": "SUPER_SECURE_PASSWORD_HASH_COME_AT_ME_NSA", "token": "IM_A_TOKEN_GAIS_SRSLY", "username": "jim_bob"}}

As you can see, _id and password are still there. What am I doing wrong? Any help would be greatly appreciated.

Thank you!

like image 965
Z. Charles Dziura Avatar asked Sep 13 '13 17:09

Z. Charles Dziura


1 Answers

The user parameter that is returned from the call is an instance of a Model, in this case, the User.

If you want to use it as a raw JavaScript object, then you'd need to convert it using toObject. This returns a plain-old JavaScript object. With that, you can use delete and remove whatever properties you'd like.

user = user.toObject(); // swap for a plain javascript object instance delete user["_id"]; delete user["password"]; return callback(null, new SuccessEnvelope(user)); 
like image 86
WiredPrairie Avatar answered Oct 08 '22 00:10

WiredPrairie