Reputation: 319
I have created custom javascript function in mongodb.
db.system.js.save(
{
_id : "generateSRID" ,
value : function (zone_id, length){ var randomNum = (Math.pow(10,length).toString().slice(length-1) + Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length); return 'SR'+zone_id+'-' + randomNum; }
});
I have mongoose schema ,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
type: {type: String, required: true},
service: {type: String, required: true},
object: {type: String, required: true},
method: {type: String, required: true},
log: {type:String, required: true},
srid : {type: String} <== need to generate while saving
});
module.exports = mongoose.model('Logger', schema);
My question is that, how can i access custom function while saving schema? Is it possible, if no - what is the alternative.
var data = {
"type" : "Info",
"service" : "customerService",
"object" : "customer.controller",
"method" : "getCustomerByMSISDN",
"log" : "INVOKE:getCustomerByMSISDN",
"srid" : generateSRID(2,10) <== access mongodb fuction
};
const logger = new Logger(data);
logger.save(function(err, result) {
if (err) {
console.log(err);
}
console.log("## Log created successfully ##");
});
Upvotes: 1
Views: 227
Reputation: 2810
You can achieve this by using pre-save of mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
type: {type: String, required: true},
service: {type: String, required: true},
object: {type: String, required: true},
method: {type: String, required: true},
log: {type:String, required: true},
srid : {type: String } <== need to generate while saving
});
schema.pre('save', function(next) {
this.srid= '1234';
next();
});
module.exports = mongoose.model('Logger', schema);
Note: For update use pre-update
Upvotes: 1