I am working with a Node application that uses mongoose , mongodb and restify . I would like to know if it is good practice to have an import code from different models when defining a route function. This should be a fairly simple question, I just need a guide, and I can encode it myself. Thanks for taking the time to read this.
I know how to define a relationship, but I'm not sure how I should make an actual relationship. That is, in other words, when a car is created, what is the best way to add a car to it.
Please note that I am trying to keep this api RESTful.
I have two models that I would have to link based on the following schema, which is stored in db/schema.js :
//schema.js var restify = require('restify'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; // User Schema exports.User = new Schema({ id: ObjectId, name: String, cars: [{ type: ObjectId, ref: 'Car' }], }); // Car Schema exports.Car = new Schema({ id: ObjectId, name: String, _user: { type: ObjectId, ref: 'User' }, });
Then I create models in models/... , where I have a different file for each model. Now each of them has only one line of code, but I left them as independent files when I need to write model methods.
In models/car.js :
mongoose.model('Car', db_schema.Car);
In models/user.js :
mongoose.model('User', db_schema.User);
And finally, I set up a route with a message and put the requests in routes/cars.js
This is not all, it is just necessary to answer my question.
module.exports = function(app) { function putCar(req, res, next) { Car.findById(req.params.id, function (err, car) { if (!err) { car.name = req.params.name; car.save(function (err) { if (!err) { // PLACE A // current_user = get current user from session // current_user.cars.push(car); res.send(car); return next(); } else { return next(new restify.InternalError(err)); } }); } else { return next(new restify.MissingParameterError('ObjectId required.')); } }); } function postCar(req, res, next) { var car = new Car(req.params); car.save(function (err, car) { if (!err) { // PLACE B // current_user = get current user from session // current_user.cars.push(car); res.send(car); } else { return next(err); } }); } app.post('api/car', postCar); app.put('/api/car', putCar); }
Would it be appropriate to have a code, such as pseudocode, in place A and place B? The problem that comes to my mind is that I need to require a User model in the routes / cars.js file, which makes things less modular. Would it be better to do this in / car.js models?