Solvedmongoose Allow import { model } from mongoose

It's common when user wants to import variables from module without saving module into a variable, e.g.

let {Schema} = require('mongoose');

or

var Schema = require('mongoose').Schema;

but when I do this with model

var model = require('mongoose').model;

and try to create a model with imported function, I have an error

TypeError: Cannot read property 'modelSchemas' of undefined

Yes, model is a property of Mongoose.prototype, but Schema also is.
If documentation contains an instruction like

var Schema = mongoose.Schema,
...

it's possible to assume that 'model' will have similar behavior

15 Answers

✔️Accepted Answer

+1

Currently this doesn't work:

import { model } from 'mongoose'

Other Answers:

Supporting this behavior would involve a massive refactor of mongoose connections. Long story short, require('mongoose').model(); is different than var model = require('mongoose').model; model(); because the value of this in the former function call is the require('mongoose'); singleton, whereas it is the global object in the latter call. If you want a workaround, model.call(require('mongoose'), 'MyModelName', schema); should work fine. I'm not a huge fan of the fact that mongoose's top level functions are laden with side effects, but to get rid of that we'd also have to get rid of the mongoose.model() getter syntax, which would break a lot of people's code.

In 5.3.14, you'll be able to do import {model} from 'mongoose' and it will work properly. That is just for this one function though, we still need more work to support that for the rest of the Mongoose global API. We'll still warn against doing this and keep the section in the FAQ, but the model case is so frequent that we can fix it as a one-off.

I'll +1 this.

import { model } from 'mongoose'

^ is a handy/attractive syntax.