Max Schmitt

November 30 2020

Mongoose: Instantiate Document from Schema

I recently came across a scenario where I wanted to instantiate a Mongoose Document from a Schema.

Normally I would simply instantiate the Model but I wanted to make this possible without having to register a Model in the first place.

So here's how you can instantiate a Mongoose Document without a complementary Model:

JS

// Create schema
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
})
// Instantiate document
const user = new mongoose.Document({ name: 'Max', password: '•••••••••' }, UserSchema)