简体   繁体   中英

Cannot overwrite `users` model once compiled

class UserModel {
    initSchema() {
        const schema = new Schema({
            name: "string",
            email: "string",
            password: "string",
        });
        mongoose.model("users", schema);
    }
    getInstance() {
        this.initSchema();
        return mongoose.model("users");
    }
}

export default UserModel;



export class UserModel extends BaseModel {
    constructor(model: any) {
        const dataAccess = new DataAccess();
        model = dataAccess.getSchema("users");
        super(model);
    }
}




class DataAccess {
    getSchema = (schema: any) => {
        return mongoose.model(schema);
    }
}

** The DataAccess class can be assigned to the BaseService for the data manipulation(CRUD)**

** I am getting error of the database can not be override when I am performing an Operation**

Also Confused How to Pass The Name of The UserModel to The DataAccess Class Method So I Can Use It In BaseService For The Data Manipulation

I think the problem is that you are trying to overwrite your model every time you init it. If you want to use initSchema first you need to check if is it registered:

    initSchema() {
        if (mongoose.models.users) {
            return;
        }

        const schema = new Schema({
            name: "string",
            email: "string",
            password: "string",
        });
        mongoose.model("users", schema);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM