[英]extends schema in mongoose and nodejs
i have some field and it reapet in all of my models.我有一些领域,它在我所有的模型中重复出现。
i create a BaseSchema
in in other file from my models:我在我的模型的其他文件中创建了一个BaseSchema
:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var util = require('util');
function BaseSchema() {
Schema.apply(this, arguments);
this.add({
owner: { type:String },
updateDate: { type: String },
updateBy: { type: String },
deleteDate: { type: String },
deleteby: { type: String },
createDate: { type: String },
createBy: { type: String },
});
}
util.inherits(BaseSchema, Schema);
and i use this BaseSchema
in RoleSchema
:我在RoleSchema
BaseSchema
const mongoose = require("mongoose");
const schema = mongoose.Schema;
const BaseSchema = require("./baseEntity");
const RoleSchema = new BaseSchema.add({
name: { type: String, require: true },
description: { type: String },
scurityStamp: { type: String, require: true },
});
RoleSchema.pre('save',()=>{
scurityStamp='kianoush'
})
mongoose.model('Roles',RoleSchema);
but when i run the project it show me this error:但是当我运行该项目时,它向我显示了这个错误:
const RoleSchema = new BaseSchema.add({
^
TypeError: BaseSchema.add is not a constructor
at Object.<anonymous> (F:\Projects\Nodejs\SalesSignal\src\entity\role.js:5:20)
whats the prboem?什么是问题? how can i solve this problem???我怎么解决这个问题???
I think this can be simplified as you're basically trying to extend your BaseSchema
:我认为这可以简化,因为您基本上是在尝试扩展BaseSchema
:
import { model, Schema } from 'mongoose';
const BaseSchema = new Schema({
owner: { type:String },
updateDate: { type: String },
updateBy: { type: String },
deleteDate: { type: String },
deleteby: { type: String },
createDate: { type: String },
createBy: { type: String },
});
const RoleSchema = new Schema({
...BaseSchema.obj,
name: { type: String, required: true },
description: { type: String },
scurityStamp: { type: String, required: true },
});
// test
const RoleModel = mongoose.model('roles', RoleSchema);
const role = new RoleModel({ name: 'test', scurityStamp: 'test', owner: 'someOwner', createDate: new Date() });
await role.save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.