Find Mongoose Model by Model Name
I Am Trying to Set up Different Models with the Same Schema for Look up Purposes, but I Am Running into an Error When I Try to Find the Model by the Name Given...
I am trying to set up different models with the same schema for look up purposes, but I am running into an error when I try to find the model by the name given to it. I get the error "Schema hasn't been registered for model "model1", but the model is clearly shown in the database. The following is the code for setting up the model:
const model = mongoose.model(modelname, Schema)
var doc = new model({var1, var2, var3});
doc.save().then((resp) => {
return res.status(200).json(resp);
})
The following is the code for accessing the model again in a different route:
var model = mongoose.model(modelname, Schema);
The issue is that the model name is a variable, so I will never know the exact model being accessed
edit: schema
const Schema = new Mongoose.Schema({
var1: String,
var2: String,
var3: String
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
1 Answer
Not Correct, Want Update
I think, when u use var model = mongoose.model(modelname, Schema); mongoose will register this to database so it cause error duplicate with same modelname.
And if want to have more model to one Schema, I think u use different modelname
If u want to connect to one model, u can use exports and require to get
const User = mongoose.model('User', UserSchema);
export default User;
// other file
import UserModel from "./userModel.js";