5

I am using node v8.11, not able to delete an item from the object which creates and returns new object from the mongoDB.

Sample response after creating:

{
    "name": "",
    "device": "",
    "session":"",
    "_id": "5b7e78c3cc7bca3867bbd1c9",
    "createdAt": "2018-08-23T09:05:07.134Z",
    "updatedAt": "2018-08-23T09:05:07.134Z",
    "__v": 0
}

Trying to remove "_id" from the response like below:

tokens.create(req.body).then(function(session){
     delete session._id;
     return res.send(session); // _id still exist
});

I have seen the delete is deprecated in ES6, is this case issue? How can I delete an Item, in one line using the key?

3
  • 2
    Mongoose returns bson types so you need to convert it to pure javascript object. Then delete might work!! Commented Aug 23, 2018 at 9:40
  • @DevangNaghera exactly what I have mentioned in the answer. That is what OP needs Commented Aug 23, 2018 at 9:41
  • @DevangNaghera - Yes, I got it. +1 Commented Aug 23, 2018 at 9:58

2 Answers 2

6

When you create a object using mongoose model then it will return you a model object instead of plain javascript object. So, when you do delete session._id; it will not work as session is a model object and it does not allow to change the property on model object directly.

You need to change the model object to plain JS object using toJSON() or toObject() method of model object and delete property on that:

tokens.create(req.body).then(function(session) {
  var sessionObj = session.toJSON();
  delete sessionObj._id;
  return res.send(sessionObj);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use destructuring and rest:

var res = {
    "name": "",
    "device": "",
    "session":"",
    "_id": "5b7e78c3cc7bca3867bbd1c9",
    "createdAt": "2018-08-23T09:05:07.134Z",
    "updatedAt": "2018-08-23T09:05:07.134Z",
    "__v": 0
};

var { _id, ...ret } = res ;

console.log(ret);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.