我试图覆盖mongoose模型的setter,因为我想创建自己的Date对象,但检查documentation我做了以下但是仍未调用setter:
var mongoose = require('mongoose');
function strToDate(dateStr){
var dateStr = dateStr.split('/');
console.log('parsed a date!');
return new Date(dateStr[0],dateStr[1],dateStr[2],dateStr[3],dateStr[4], dataStr[5]);
}
var infoSchema = new mongoose.Schema({
code: {type : String, require: true},
valve: {type : Number, require: true},
dataTime: {type: Date, require: true, set: strToDate},
status: {type: Boolean, require: true, default: false },
elapsedTime: 0
});
var dataLogSchema = new mongoose.Schema({
boardId: {type: String, require: true, unique: true},
logInfo:[infoSchema]
});
module.exports = mongoose.model('DataLog', dataLogSchema);
有什么不对?我使用的是mongoose 4.0.5
答案 0 :(得分:0)
我用mongoose 4.0.6尝试了这个例子
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var InfoSchema = new Schema({
dataTime: {type: Date, require: true, set: strToDate}
});
function strToDate(stringDate) {
var sDate = stringDate.split('/');
return new Date(sDate[0], sDate[1], sDate[2], sDate[3], sDate[4], sDate[5]);
}
var Info = mongoose.model('Info', InfoSchema);
var info = new Info();
info.dataTime = '1995/11/17/3/24/0';
console.log(info.dataTime); //Sun Dec 17 1995 03:24:00 GMT-0400 (BOT)
答案 1 :(得分:0)
问题是你的strToDate
函数中有一个拼写错误导致函数抛出ReferenceError
异常(Mongoose显然只是吃掉它)。 dataStr[5]
应该是dateStr[5]
。
所以只需将该函数的最后一行更改为:
return new Date(dateStr[0],dateStr[1],dateStr[2],dateStr[3],dateStr[4],dateStr[5]);