[英]Deleting _id from object coming from mongodb doesn't work
I am using graphql to get some data from mongodb database.我正在使用 graphql 从 mongodb 数据库中获取一些数据。 So, I was making an api which on running saves data in main collection but also saves data in some other collection with a couple of more data.
所以,我正在制作一个 api ,它在运行时将数据保存在主集合中,但也会将数据保存在其他一些集合中以及更多数据。 I was trying to delete
_id
from the data that I get on saving on main collection but it's not working and I can't figure out why.我试图从保存在主集合上的数据中删除
_id
,但它不起作用,我不知道为什么。
Here's what's happening这是正在发生的事情
const data = await User.getResolver('updateById').resolve({ //default resolver from graphql-compose library to update a record. Returns the whole document in record //
args: {...rp.args}
})
const version = '4'
const NewObject = _.cloneDeep(data.record);
NewObject.version = version;
NewObject.oldId = data._id;
_.unset(NewObject, '_id'); //this doesn't work neither does delete NewObject._id//
console.log('new obj is', NewObject, version, NewObject._id, _.unset(NewObject, '_id')); //prints _id and surprisingly the unset in console.log is returning true that means it is successfully deleting the property//
I am very confused to what I am doing wrong.我对自己做错了什么感到非常困惑。
Edit: Sorry should have mentioned, but according to lodash docs _.unset
returns true
if it successfully deletes a property.编辑:抱歉应该提到,但根据lodash docs
_.unset
如果成功删除属性,则返回true
。
Turn's out mongoDb makes _id
as a Non configurable property.结果是 mongoDb 使
_id
成为不可配置的属性。 So, to do this I had to make use of toObject()
method to make an editable copy of my object.因此,为此,我必须使用
toObject()
方法制作 object 的可编辑副本。
const NewObject = _.cloneDeep(data.record).toObject();
With this I was able to delete _id
.有了这个我可以删除
_id
。 Alternatively _.omit of lodash also works.或者_.omit的 lodash 也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.