Reputation: 206
I'm getting an error for trying to include a mongoose model written in a separate file.
throw new mongoose.Error.MissingSchemaError(name);
MissingSchemaError: Schema hasn't been registered for model "Cart".
Use mongoose.model(name, schema)
Within my server.js file my mongo models are defined before I call my routes. Which I've looked around and found defining your models after the routes are the cause of this error but that's not my case.
//Require db config
require('./app_api/config/model.js');
//Require routes config
var routesAPI = require('./app_api/config/routes.js')
var app = express();
Within my model.js file I require my separate schemas.
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/followdata';
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
console.log('Mongoose disconnected');
});
// SCHEMA DECLERATION
require('../models/user');
require('../models/userCart');
So I'm not really sure what the problem is.
This is how I try to bring in my cart model into my user model schema.
var mongoose = require( 'mongoose' );
var jwt = require('jsonwebtoken');
var crypto = require('crypto');
var Cart = mongoose.model('Cart');
var Schema = mongoose.Schema;
var userSchema = new Schema({ ......... });
And within my userCart.js file I export it properly.
module.exports = mongoose.model('Cart', cartSchema);
Upvotes: 1
Views: 1179
Reputation: 638
You need to require in your Cart
schema if you want to use it in your User model schema.
So, you would need var Cart = require('yourPathToCart/cart')
instead of var Cart = mongoose.model('Cart')
(the previous line of code is attempting to create a new model named Cart and this is where your error is coming from) in your User model schema file.
Upvotes: 1