不能对猫鼬查询结果使用“删除”运算符

Gle*_*enn 5 javascript mongoose mongodb node.js express

我试图在将数据发送回浏览器之前删除一个密钥。出于某种原因,也许是因为它是一个猫鼬对象,这不起作用:

delete myObject.property
Run Code Online (Sandbox Code Playgroud)

如果我这样做console.log(delete myObject.property),我得到true我的理解方式的财产不会被删除。我怎样才能摆脱这把钥匙?

(更多背景:我知道我可以通过使用 mongoose 选择查询来取消它,但我确实需要最初选择键。我也可以将它设置为 null,这很好用,但我宁愿摆脱完全键)

Gov*_*Rai 6

As MikaS states, you need to convert to convert the Mongoose document object into an ordinary object first:

const newObj = myObject.toObject();
delete newObj.property;
Run Code Online (Sandbox Code Playgroud)

This should be fine if you're doing this once. However, if you have to repeat this logic everywhere you return this this type of document with certain keys omitted or other transformations, you should define transformations on your schema:

// 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' }
Run Code Online (Sandbox Code Playgroud)

Read about Document#toObject and transformations in the docs