我试图在将数据发送回浏览器之前删除一个 key 。出于某种原因,也许是因为它是 Mongoose 对象,这不起作用:
delete myObject.property
如果我执行 console.log(delete myObject.property)
,我得到 true
,我理解这意味着该属性未被删除。我怎样才能摆脱这把 key ?
(更多背景:我知道我可以通过使用 mongoose 选择查询将其关闭,但我确实需要在开始时选择 key 。我也可以将它设置为 null,这很好用,但我更愿意得到完全摆脱 key )
最佳答案
正如 MikaS 所述,您需要先将 Mongoose 文档对象转换为普通对象:
const newObj = myObject.toObject();
delete newObj.property;
如果您只执行一次,应该没问题。但是,如果您必须在返回此类文档的任何地方重复此逻辑并省略某些键或进行其他转换,则应在您的架构上定义转换:
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// any kind of simple/complicated transformation logic here
// remove the _id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
doc.toObject(); // { name: 'Wreck-it Ralph' }
关于javascript - 不能对 mongoose 查询结果使用 "delete"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48197334/