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 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'
    }
});
2

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";
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest