我已经在mongodb中创建了自定义javascript函数。
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; }
});
我有猫鼬模式,
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);
我的问题是,在保存架构时如何访问自定义功能? 如果没有,有可能吗?替代方法是什么。
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 ##");
});
答案 0 :(得分:0)
您可以通过预先保存猫鼬来实现这一目标
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);
注意:要进行更新,请使用更新前