猫鼬将返回的数据限制为模型

时间:2020-01-28 21:02:40

标签: node.js mongodb mongoose

我拥有最基本的猫鼬模式。像这样:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

ConfigSchema = new Schema({
  title: String
});

module.exports = mongoose.model("Config", ConfigSchema);

如果使用此模型从此集合中获取数据(使用find),则会得到整个对象。
致电:

Config.find(function(err, configs) {
  if (err) res.send(err);
  res.json(configs);
});

返回的数据:

enter image description here

我以为Mongoose会针对模型验证提取的数据,以仅返回适合模型的数据,因此在这种情况下,仅返回元素的标题。我知道我可以在Mongoose上使用strict属性在保存时强制执行模型,但我正在寻找的是仅获取建模数据的方法。

这里是否缺少我想要的东西,或者我只是在寻找错误的工具来实现自己想要的目标。 我发现this似乎可以满足我的要求,但我不想覆盖Mongoose模式只是为了在获取数据时强制执行它。

1 个答案:

答案 0 :(得分:1)

似乎没有内置查询功能,但您可以轻松实现自己的pre-middleware

ConfigSchema.pre('find', function() {
    this.select(Object.keys(ConfigSchema.tree));
});

当您运行Config.find时,将生成以下查询:

configs.find({}, { projection: { title: 1, _id: 1, __v: 1, id: 1 } })
相关问题