Bogdan M.
Bogdan M.

Reputation: 2181

Mongoose model definition use in different folder

I defined a schema and added a model to mongoose:

appName/models/Particiapnt.js;

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var participantSchema= new Schema({
    createdAt: { type: Date, default: Date.now },

});

var Participant = mongoose.model('Participant', participantSchema, 'participants');

module.exports = Participant;

appName/routes/api.js

var express = require('express');
var Participant = require('./models/Participant'); ---- Line of failure! ----
var router = express.Router();

router.get('/all', function(req, res) {
    Participant.find().execFind(function (arr,data) {
        res.send(data);
    });
});

module.exports = router;

In the api.js when I try to create my instance of the model I cannot since I get this:

Error: Cannot find module './models/Participant'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/../appName/routes/api.js:2:

What am I doing wrong?

Upvotes: 0

Views: 1835

Answers (1)

H&#233;ctor
H&#233;ctor

Reputation: 26034

You should put "../models/Participant" instead. In your code, you are searching for it in the same directory, but actually it is in the upper one.

Upvotes: 2

Related Questions