如何使用nodeJS从JSON对象中删除项目? [英] How to delete an Item from JSON Object using nodeJS?

查看:828
本文介绍了如何使用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);
});

这篇关于如何使用nodeJS从JSON对象中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆