简体   繁体   中英

mongoose Missing schema error while populating

I am building an app with express using mongoose as ORM for my MongoDB database.

I have 2 models located in separate files : User and Posts.

User.js model looks like

var mongoose = require('mongoose'),
    moment = require('moment'),
    Schema = mongoose.Schema,
    UserSchema = new Schema({
        created_at: {type: Date, default: moment()),
        name: String
    });
module.exports = mongoose.model('user', UserSchema);

and the Posts.js model

var mongoose = require('mongoose'),
    moment = require('moment'),
    Schema = mongoose.Schema,
    PostSchema = new Schema({
        created_at: {type: Date, default: moment()},
        user: {type: Schema.Type.ObjectId, ref: 'User'}
    });

I call them in controllers in separate files that looks like

var Post = require('../models/User'),
    User = require('../models/Posts');

Post.find().populate('user').exec();

This population returns me a MissingSchema error that says : MissingSchemaError: Schema for model 'Posts' hasn't been registerd.

The connection to the database is in the main file : app.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/database');

Can anyone tell me what's wrong with my code?

Because your reference is for " User ", I think you just have to declare your first model with correct Typpo

module.exports = mongoose.model('User', UserSchema);

instead of

module.exports = mongoose.model('user', UserSchema);

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM