节点,猫鼬:使用delete从查询结果中删除json元素 [英] Node, Mongoose: Remove json element from query result with delete

查看:57
本文介绍了节点,猫鼬:使用delete从查询结果中删除json元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这种奇怪的行为.事情是这样的:我进行数据库查询,并想删除查询返回的json元素.因此,这似乎不起作用(即未删除元素),

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;

在此有效

var user={element:json.element,blement:'stuff'}
delete user.element;

推荐答案

我认为您所指的JSON实际上是给您添加到问题中的标签的Mongoose文档对象.由于该对象已附加到其模式"中,因此您可能在其中具有诸如必填"字段之类的规则,或干扰您尝试执行的操作的规则.

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.

为了获取原始形式的Object,只需在文档结果上使用.toObject()方法:

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 );

});

当然,您始终可以使用 .select() :

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.

这篇关于节点,猫鼬:使用delete从查询结果中删除json元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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