Reputation: 13
I'm working in nodejs with Mongoose, at this moment I have data in different collections with _id like string writing for the user, I try to make a refactor of this and generate _id automatically.
I want have in other file js only function generateID( return _id; ); and implement this function in all models without write over and over in all models.
This is bus.js
/***********************************Bus Model**********************************/
var mongoose = require('mongoose'),
merge = require('merge'),
global = require('./schema/global');
/***********************************Schema******************************************/
var Schema = mongoose.Schema;
var busSchema = new Schema({});
/***********************************Methods*****************************************/
var bus = mongoose.model('Bus', busSchema);
/**
* extend functions from global
* we do this to prevent duplicate code
*/
merge(bus.schema.methods, global.schema.methods);
module.exports = bus;
And this is global.js in schema folder over models folder in project
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var globalSchema = new Schema({});
function objectIdAsString() {
return mongoose.Types.ObjectId().toString();
}
globalSchema.methods.objectIdAsString = objectIdAsString;;
module.exports = mongoose.model('global', globalSchema);
And in route.js have this implementation:
var bus = new Bus();
bus._id = bus.objectIdAsString();
Upvotes: 1
Views: 1260
Reputation: 2039
Solution is creating a Mongoose plugin
http://mongoosejs.com/docs/plugins.html
global.js
var mongoose = require('mongoose');
module.exports = exports = function objectIdAsString(schema) {
schema.methods.objectIdAsString = function objectIdAsString() {
return mongoose.Types.ObjectId().toString();
};
}
bus.js
/***********************************Bus Model**********************************/
var mongoose = require('mongoose'),
merge = require('merge'),
global = require('./schema/global');
/***********************************Schema******************************************/
var Schema = mongoose.Schema;
var busSchema = new Schema({});
/**
* extend functions from global
* we do this to prevent duplicate code
*/
busSchema.plugin(global);
module.exports = mongoose.model('Bus', busSchema);
Somewhere else:
var bus = new bus();
console.log(bus.objectIdAsString());
Is working and outputting the correct values for me:
566b35a02a54c60e168c3a9f
566b35a02a54c60e168c3aa1
566b35a02a54c60e168c3aa3
.....
Upvotes: 2