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.js
import mongoose from 'mongoose'
let userSchema = mongoose.Schema({
password: String,
username: String
})
userSchema.methods.setUp = function (username, password) {
this.username = username
this.password = password
return this
}
export let User = mongoose.model('User', userSchema)
export default User
// routes.js
import { User } from './models/user'
router.post('/newuser', function (req, res) {
new User()
// 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""