MongooseJS 4.9.8如何定义可复用的自定义类型?
实现Mongoose可复用的Location类型(v4.9.8)
没问题,在Mongoose 4.9.8里实现可复用的Location类型非常容易,通过定义子Schema就能搞定,这样你可以在任意其他Schema里重复引用它,既保证结构一致性,又能减少重复代码。
步骤1:定义独立的Location子Schema
首先把Location的结构单独定义成一个Schema,之后所有需要用到这个结构的地方都可以直接引用它:
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // 可复用的Location子Schema const locationSchema = new Schema({ city: { type: String, required: false }, state: { type: String, required: false }, country: { type: String, required: false } });
步骤2:在目标Schema中引用Location类型
现在你可以在thingsSchema(或者任何其他Schema)里直接使用这个子Schema作为字段类型:
const thingsSchema = new Schema({ thing: { type: String, required: false }, // 引用之前定义的locationSchema location: locationSchema });
步骤3:在其他Schema中复用(示例)
比如你要在用户Schema里同时用到家庭地址和工作地址,直接重复引用即可:
const userSchema = new Schema({ name: String, homeAddress: locationSchema, workAddress: locationSchema });
进阶:抽成单独文件维护
如果项目规模较大,建议把Location子Schema单独放到一个文件里(比如./schemas/location.js),方便统一维护:
// ./schemas/location.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const locationSchema = new Schema({ city: { type: String, required: false }, state: { type: String, required: false }, country: { type: String, required: false } }); module.exports = locationSchema;
然后在需要的文件里引入使用:
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // 引入Location子Schema const locationSchema = require('./schemas/location'); const thingsSchema = new Schema({ thing: { type: String, required: false }, location: locationSchema });
这种方式在Mongoose 4.x版本里完全兼容,后续如果需要修改Location的字段(比如新增zipCode或者修改必填规则),只需要修改这一个子Schema文件,所有引用它的地方都会同步生效,完美解决复用和一致性的问题。
内容的提问来源于stack exchange,提问作者j-p
相关产品推荐
相关产品推荐

