如何使用nodeJS从JSON对象中删除项目?
我正在使用节点v8.11,无法从该对象删除一个项目,该对象会从mongoDB创建并返回新对象.
I am using node v8.11, not able to delete an item from the object which creates and returns new object from the mongoDB.
创建后的示例响应:
{
"name": "",
"device": "",
"session":"",
"_id": "5b7e78c3cc7bca3867bbd1c9",
"createdAt": "2018-08-23T09:05:07.134Z",
"updatedAt": "2018-08-23T09:05:07.134Z",
"__v": 0
}
尝试从响应中删除"_id",如下所示:
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
});
我已经看到在ES6中不建议使用删除方法,这是这种情况吗? 如何使用密钥在一行中删除项目?
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?
使用猫鼬模型创建对象时,它将返回一个模型对象,而不是普通的javascript对象.因此,当您执行delete session._id;
时,它将不起作用,因为session
是模型对象,并且不允许直接更改模型对象的属性.
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.
您需要使用模型对象的toJSON()
或toObject()
方法将模型对象更改为普通JS对象,并删除其上的属性:
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);
});