I'm working an a Node app that uses mongoose, mongodb, and restify. I'd like to find out as to whether it is good practice to have import code from various models when defining the route function. This should be a fairly straightforward question, I just need guidance and I'll be able to code it myself. Thanks for taking the time to read this.
I know how to define the relationship, but I'm not sure how I should be making the 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 linked 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 build the models in models/..., where I have a different file for each model. Right now they each only have one line of code but I left them as independent files for 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 the route with the post and put requests in routes/cars.js
This isn't all of it, just the 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 code such as the pseudocode in place A and place B? The issue that comes to my mind is that I need to require the User model in the routes/cars.js file, which makes things less modular. Would it be better do this in models/car.js?