我有一个文章模型定义为:
var ArticleSchema = new Schema({
type: String
,title: String
,content: String
,comments: [{
type: Schema.ObjectId
,ref: 'Comment'
}]
,replies: [{
type: Schema.ObjectId
,ref: 'Reply'
}]
,feedbacks: [{
type: Schema.ObjectId
,ref: 'Feedback'
}]
,meta: {
tags: [String] //anything
,apps: [{
store: String //app store, google play, amazon app store
,storeId: String
}]
,category: String
}
//normal, deleted, banned
, status: String
,statusMeta: {
createdBy: {
type: Schema.ObjectId
,ref: 'User'
}
,createdDate: Date
, updatedBy: {
type: Schema.ObjectId
,ref: 'User'
}
,updatedDate: Date
,deletedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,deletedDate: Date
,undeletedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,undeletedDate: Date
,bannedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,bannedDate: Date
,unbannedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,unbannedDate: Date
}
})
我有以下代码来创建新文章并保存。
var newArticle = new Article()
newArticle.status = helper.constant.articleTypes.other
newArticle.type = req.body.type
newArticle.category = req.body.category
newArticle.title = req.body.title
newArticle.content = req.body.content
newArticle.meta = req.body.meta
newArticle.statusMeta.createdBy = req.user
newArticle.statusMeta.createdDate = new Date
newArticle.save(function(err) {
if (err)
return next(err)
}
我的预保存钩子(帮助函数)
exports.batchValidationWrapper = function(schema, module, fieldPaths) {
for (var i = 0; i < fieldPaths.length; i++) {
var fieldPath = fieldPaths[i]
;(function(fieldPath) {
schema.pre('save', true, function(next, done) {
var self = this
var validationFunction = exports.validation[module][fieldPath]
var msg = validationFunction(self[fieldPath])
if (msg) {
self.invalidate(fieldPath, msg)
done(msg)
}
else {
done()
}
})
})(fieldPath)
}
}
在我的模型中,我打电话给助手
helper.batchValidationWrapper(ArticleSchema, 'article', [
'type'
,'title'
,'content'
,'comments'
,'replies'
,'feedbacks'
,'meta.tags'
,'meta.apps'
,'meta.category'
,'status'
,'statusMeta.createdBy'
,'statusMeta.createdDate'
,'statusMeta.deletedBy'
,'statusMeta.deletedDate'
,'statusMeta.undeletedBy'
,'statusMeta.undeletedDate'
,'statusMeta.bannedBy'
,'statusMeta.bannedDate'
,'statusMeta.unbannedBy'
,'statusMeta.unbannedDate'
])
helper.validation定义如下。它基本上是一堆接收输入并返回错误消息(如果有)的函数。如果没有错误,请返回
''
exports.article = {
type: function(input) {
if (!input)
return 'type is requried'
return passIfAmongTypes('Article', input, constant.articleTypes)
}
,'statusMeta.createdDate': function(input) {
if (!input)
return 'created date is required'
return ''
}
}
尝试创建新文章时,我说
created date is required
时出错。我尝试了
newArticle.markModified('statusMeta')
和newArticle.markModified(statusMeta.createdDate
),两者均无法正常工作。我认为没有必要将其标记为已修改,因为它是nested object
类型,而不是mixed
类型(来自mongoose doc)我也尝试设置
newArticle.statusMeta = {}
,但也不起作用。当我设置断点时,newArticle.statusMeta.createdDate是未定义的
我不想为createdDate使用默认值的原因是,设置默认值似乎发生在运行pre('save')挂钩之前,这使我的验证代码始终失败
最佳答案
这是我自己的错误。在helper.js
内部,我使用helper.funcName()
而不是exports.funcName()
。即使使用webstorm IDE,也很难在javascript中进行调试。