Max SchmittMS
30th November 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:

// 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
)
Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, feel free to contact me.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.