我在我的express.js项目中使用mongoose。
这是我的文章模型:
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
}
, 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
}
}, {minimize: false})
这是我的控制器功能
exports.createArticle = function(req, res, next) {
//1. save article
var newArticle = new Article()
newArticle.status = helper.constant.entityStatus.normal
newArticle.type = req.body.type
newArticle.category = req.body.category
newArticle.title = req.body.title
newArticle.content = req.body.content
//comments omit
//replies omit
//feedbacks omit
newArticle.meta = req.body.meta
newArticle.statusMeta.createdBy = req.user
newArticle.statusMeta.createdDate = new Date
newArticle.save(function(err) {
if (err)
return next(err)
//2. add article to user
req.user.articles.push(newArticle)
req.user.save(function(err) {
if (err)
return next(err)
//3. refetch article, done
var query = Article.findById(newArticle._id)
helper.populateCommonFieldsForQuery(query)
query.exec(function(err, article) {
if (err)
return next(err)
if (! article)
return next(helper.getGeneralError('unable to fetch saved article'))
return res.json(helper.dataAppendedWithMessage(article.toJSON(), 'success', 'successfully created article'))
})
})
})
}
当我用meta.tags
创建一个空数组的文章时,一切正常。如果标记不为空,则不会触发保存回调(function(err) {}
)。
答案 0 :(得分:0)
在保存之前写下这个:
newArticle.markModified('meta');
答案 1 :(得分:0)
这是我自己的代码的错误。在helper.js
内,我使用了helper.functionName()
而不是exports.functionName()
,这是未定义的。在javascript中抓住这些错误很难