javascript - MissingSchema Error: Schema hasn't been registered for model "User" -
i keep getting error whenever launch application:
--missingschema error: schema hasn't been registered model "user" --
i'm working tutorial "mongoose application development" book simon holmes. i'm @ chapter 5 "interacting data - creation"
here's code:
app.js:
var express = require('express') , routes = require('./routes') , user = require('./routes/user') , project = require('./routes/project') , http = require('http') , path = require('path');
db.js:
//creating application schemas: //==================================== //user schema: //=============== var userschema = new mongoose.schema({ name: string, email: {type: string, unique:true}, createdon: { type: date, default: date.now }, modifiedon: date, lastlogin: date }); //build user model: //=========================== mongoose.model( 'user', userschema );
user.js:
var mongoose = require("mongoose"); var user = mongoose.model( 'user' );
error results:
throw new mongoose.error.missingschemaerror(name); ^ missingschemaerror: schema hasn't been registered model "user". use mongoose.model(name, schema) @ mongoose.model (c:\users\new\desktop\mongoose_pm_app\ mongoosepm\node_modules\mongoose\lib\index.js.311.13) @ object. <anonymous> (c:\users\new\desktop\mongoose_pm_app\mongoosepm\routes\user.js:2:21) atmodule._compile (module.js:456:26) atobject.module._extensions..js (module.js:474:10) atmodule.load (module.js:356:32) @ function.module._load (module.js:364:17) @ require (module.js:380:17) @ object <anonymous> (c:\users\new\desktop\mongoose_pm_app\mongoosepm\app.js:8:12) @ module._compile (module.js:456:26) 25 june 19:52:55 - [nodemon] app crashed waiting file changes before starting...
i'm young mongoose , mongodb. i've been through books errata pages check if mistyped same here.
i tried downloading sample code packt, sample code looks same.
any , assistance appreciated. thanks.
you need require
db.js file someplace, otherwise code in never run, , schema never registered.
also, recommend define user schema inside of user.js , add model exports, so:
user.js
//user schema: //=============== var userschema = new mongoose.schema({ name: string, email: {type: string, unique:true}, createdon: { type: date, default: date.now }, modifiedon: date, lastlogin: date }); //build user model: //=========================== var user = mongoose.model( 'user', userschema ); //exports //======= exports = user;
this allows require
file elsewhere reference user model (instead of having retrieve through mongoose.model
). example:
var user = require('user'); // ... var fred = new user({ ... }); // create new user fred.save(function (err, user) { ... });
i've not read book referred to, i'm not sure if there might reason define schemas in 1 file (which direction looked going in db.js). i've seen, it's more common have 1 schema/model per file.
Comments
Post a Comment