2014-02-18 20 views
1

我想知道是否有這樣做一個最好的方式最好的辦法:mongoosejs findByIdAndUpdate

/** 
* Article Schema 
*/ 
var PostSchema = new Schema({ 
    title: { 
     type: String, 
     required: true, 
     trim: true 
    }, 
    author:{ 
     type: String, 
     required: true, 
     default: 'whisher' 
    }, 
    slug: { 
     type: String, 
     index: { unique: true } 
    }, 
    body: { 
     type: String, 
     required: true, 
     trim: true 
    }, 
    avatar:{ 
     type: String, 
     required: true 
    }, 
    status: { 
     type: String, 
     required: true, 
     trim: true 
    }, 
    created: { 
     type: Date, 
     required: true, 
     default: Date.now 
    }, 
    published: { 
     type: Date, 
     required: true 
    }, 
    categories: { 
     type: [String] 
    }, 
    tags: { 
     type: [String], 
     required: true, 
     index: true 
    }, 
    comment: { 
     type: Schema.Types.ObjectId, 
     ref: 'CommentSchema' 
    }, 
    meta: { 
     votes: { 
      type: Number, 
      default: 0 
     }, 
     comments: { 
      type: Number, 
      default: 0 
     } 
    } 
}); 
/** 
* Comment Schema 
*/ 
var CommentSchema = new Schema({ 
    post_id: { 
     type: Schema.Types.ObjectId, 
     ref: 'Post', 
     required: true 
    }, 
    author:{ 
     type: String, 
     required: true 
    }, 
    email:{ 
     type: String, 
     required: true 
    }, 
    web:{ 
     type: String 
    }, 
    body: { 
     type: String, 
     required: true, 
     trim: true 
    }, 
    status: { 
     type: String, 
     required: true, 
     default: 'pending' 
    }, 
    created: { 
     type: Date, 
     required: true, 
     default: Date.now 
    }, 
    meta: { 
     votes: Number 
    } 
}); 
/** 
* Create a comment 
*/ 
exports.create = function(req, res) { 
    var comment = new Comment(req.body); 
    comment.save(function(err) { 
     if (err) { 
      return res.jsonp(500,{ error: 'Cannot save the comment' }); 
     } 
     Post.findById(comment.post_id).exec(function(err, post) { 
      if (err) { 
       return res.jsonp(404,{ error: 'Failed to load post with id ' + comment.post_id }); 
      } 
      if (!post) { 
       return res.jsonp(404,{ error: 'Failed to load post with id ' + comment.post_id }); 
      } 
      post.meta.comments = post.meta.comments++; 
      post.save(function(err) { 
       if (err) { 
        return res.jsonp(500,{ error: 'Cannot update the post' }); 
       } 
       res.jsonp(200,comment); 
      }); 
     }); 
    }); 
}; 

順便說一句我只是在看http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

但這樣的:

Model.findByIdAndUpdate(comment.post_id, { post.meta.comments: post.meta.comments++ }) 

犯規工作

+0

你能否確認'post.meta.comments'是在當前範圍內定義的? –

+1

這就是問題^^有沒有辦法使用填充? – Whisher

回答

3

我認爲您需要使用$inc運營商來增加t評論計數是這樣的...

Post.findByIdAndUpdate(comment.post_id, { $inc: {"meta.comments" : 1} }, callback);