gpt4 book ai didi

node.js - mongoosejs findByIdAndUpdate 一个最好的方法

转载 作者:可可西里 更新时间:2023-11-01 10:04:30 25 4
gpt4 key购买 nike

我想知道是否有最好的方法来做到这一点:

/**
* 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++ })

不工作

最佳答案

我认为您需要使用 $inc运算符像这样增加评论数...

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

关于node.js - mongoosejs findByIdAndUpdate 一个最好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com