如何在Mongoose的Author Schema中自动关联填充Book数据?
Mongoose实现关联字段自动填充(无需手动调用populate)
可以实现自动填充关联字段,无需每次查询都手动调用populate,下面提供两种常用方案:
方法一:使用预查询中间件(无需额外插件)
直接在Author Schema中添加预查询钩子,让所有find类查询自动执行填充逻辑:
const mongoose = require("mongoose"); const schema = new mongoose.Schema( { fullname: { type: String, required: true, trim: true, }, book: { type: mongoose.Schema.Types.ObjectId, ref: "book", }, } ); // 为find、findOne、findById等查询添加自动填充 schema.pre(['find', 'findOne', 'findById'], function(next) { // 配置字段映射,将Book的bookname转为输出的name,隐藏_id this.populate({ path: 'book', select: { name: '$bookname', _id: 0 } }); next(); }); const Authors = mongoose.model("author", schema); module.exports = Authors;
使用时直接查询即可,无需手动调用populate:
const author = await Author.findOne({ fullname: "bob" });
方法二:使用mongoose-autopopulate插件(更简洁)
- 先安装插件:
npm install mongoose-autopopulate
- 修改Author Schema,为关联字段开启自动填充:
const mongoose = require("mongoose"); const autopopulate = require('mongoose-autopopulate'); const schema = new mongoose.Schema( { fullname: { type: String, required: true, trim: true, }, book: { type: mongoose.Schema.Types.ObjectId, ref: "book", // 配置自动填充及字段映射 autopopulate: { select: { name: '$bookname', _id: 0 } } }, } ); // 注册插件 schema.plugin(autopopulate); const Authors = mongoose.model("author", schema); module.exports = Authors;
查询时同样无需手动调用populate,自动返回符合预期格式的结果。
说明:两种方法均满足需求,若你的Mongoose版本在6.x及以上,插件方法更简洁;若想避免额外依赖,预中间件方法更合适。
内容的提问来源于stack exchange,提问作者Daxcor
相关产品推荐
相关产品推荐

