Skip to content Skip to sidebar Skip to footer

Cannot Instantiate Mongoose Schema: "object Is Not A Function"

In my routes/index.js file, I have: var mongoose = require('mongoose/'); ... var schema = mongoose.Schema; var user_details = new schema( { username: String, password: Str

Solution 1:

The error is being triggered because a schema cannot be instantiated and used as a model. You need to make it a mongoose model first with mongoose.model('DocumentName', document).

For example (I'm copypasta'ing part of this from a current project, so it's ES6):

// user.jsimport mongoose from'mongoose'let userSchema = mongoose.Schema({
    password: String,
    username: String
})

userSchema.methods.setUp = function (username, password) {
    this.username = username
    this.password = password
    returnthis
}

exportletUser = mongoose.model('User', userSchema)
exportdefaultUser// routes.jsimport { User } from'./models/user'

router.post('/newuser', function (req, res) {
    newUser()
    // note the `setUp` method in user.js
    .setUp(req.params.username, req.params.password)
    .save()
    // using promises; you can also pass a callback// `function (err, user)` to save
    .then(() => { res.redirect('/') })
    .then(null, () =>/* handle error */ })
})

Post a Comment for "Cannot Instantiate Mongoose Schema: "object Is Not A Function""