read/find 上的 Mongoose 删除不在架构上的字段
Mongoose Remove Fields not on schema on read/find
我有一个模式:
const LinkSchema = new mongoose.Schema({
name: { type: String },
style: { default: "icon", type: String },
});
并且文档已经在 mongoDB 中,可能有很多旧字段。
{
"name": "abcLink",
"oldThing1": true,
"oldThing2": "oeunth",
....
"oldThing100": "hi",
}
我想要 link.findOne({ name: "abcLink" })
到 return
{
"name": "abcLink",
"style": "icon"
}
目前,我得到
{
"name": "abcLink",
"oldThing": true,
"style": "icon"
}
我如何才能 strict
读取以取回过滤对象,其中架构中未定义的任何字段都未被 return 编辑?
因为我们有 30 多个活动字段和许多非活动字段,所以重要的是我们可以定义架构一次,然后自动过滤结果。我们不想在多个地方重复有效或无效的字段。注意:在架构上使用 Object.keys
之类的函数来获取有效字段的数组并使用它进行过滤是完全可以接受的。
您可以像这样使用转换函数覆盖 toJSON
方法,这样它就没有任何不在架构中的字段。
const mongoose = require("mongoose");
const LinkSchema = new mongoose.Schema({
name: { type: String },
style: { default: "icon", type: String }
});
var schemaFields = Object.keys(LinkSchema.paths);
LinkSchema.set("toJSON", {
transform: function(doc, ret, options) {
let result = {};
Object.keys(ret).map(key => {
if (schemaFields.includes(key)) {
result[key] = ret[key];
}
});
return result;
}
});
module.exports = mongoose.model("Link", LinkSchema);
按照@Loren 在评论中提到的更新,对于嵌套对象,我们可以使用 Object.keys(LinkSchema.tree)
而不是 Object.keys(LinkSchema.paths)
。
我有一个模式:
const LinkSchema = new mongoose.Schema({
name: { type: String },
style: { default: "icon", type: String },
});
并且文档已经在 mongoDB 中,可能有很多旧字段。
{
"name": "abcLink",
"oldThing1": true,
"oldThing2": "oeunth",
....
"oldThing100": "hi",
}
我想要 link.findOne({ name: "abcLink" })
到 return
{
"name": "abcLink",
"style": "icon"
}
目前,我得到
{
"name": "abcLink",
"oldThing": true,
"style": "icon"
}
我如何才能 strict
读取以取回过滤对象,其中架构中未定义的任何字段都未被 return 编辑?
因为我们有 30 多个活动字段和许多非活动字段,所以重要的是我们可以定义架构一次,然后自动过滤结果。我们不想在多个地方重复有效或无效的字段。注意:在架构上使用 Object.keys
之类的函数来获取有效字段的数组并使用它进行过滤是完全可以接受的。
您可以像这样使用转换函数覆盖 toJSON
方法,这样它就没有任何不在架构中的字段。
const mongoose = require("mongoose");
const LinkSchema = new mongoose.Schema({
name: { type: String },
style: { default: "icon", type: String }
});
var schemaFields = Object.keys(LinkSchema.paths);
LinkSchema.set("toJSON", {
transform: function(doc, ret, options) {
let result = {};
Object.keys(ret).map(key => {
if (schemaFields.includes(key)) {
result[key] = ret[key];
}
});
return result;
}
});
module.exports = mongoose.model("Link", LinkSchema);
按照@Loren 在评论中提到的更新,对于嵌套对象,我们可以使用 Object.keys(LinkSchema.tree)
而不是 Object.keys(LinkSchema.paths)
。