Reputation: 488
My project looks like this:
My problem is that im going through a tutorial, http://youtu.be/5e1NEdfs4is . but i want to handle all paths in index.js that the tutorial does in app.js
In my index.js i do the following:
router.route('/api/bears')
//create a bear (Accessed at POST http://localhost:3000/api/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the bear model
bear.name = req.body.name; // set the bears name (comes from post request)
//save the bear and check for errors
bear.save(function(err) {
if(err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
// get all the bears (accessed at GET http://localhost/api/bears)
.get(function(req, res) {
Bear.find(function(err, bears) {
if(err)
res.send(err);
res.json(bears);
});
});
In app.js is this to load all models:
//load all files in models dir
fs.readdirSync(__dirname + '/app/models').forEach(function(filename) {
if (~filename.indexOf('js')) require(__dirname + '/app/models/' + filename)
});
and in index.js i want to declare variable:
var Bear = require('./app/models/bear');
but this doesn't seem to work.
I get the error:
bear.js if looking like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
If im doing something superwrong with node.js it's because im very new to it and have never used javascript at all.
thankful for all help I can get!
Upvotes: 0
Views: 1334
Reputation: 8922
Okay, so it seems that you have to get back from one folder.
In fact, with nodejs, you have to specify the path FROM your current directory.
If you need to require bear in index.js (which is in route folder) you'll have to make something like :
var Bear = require('../yourfolder')
Upvotes: 1