【发布时间】:2021-12-05 00:04:38
【问题描述】:
我有一个使用 Node.js、Mongoose、MongoDB 和 MongoDB Compass 的博客应用程序。 我的目标是计算每个帖子有多少浏览量。 为此,我创建了一个“帖子”模型架构,当然还有一条通往帖子的路线。 我还发现有一个 $inc 方法可以增加数据库中的值。 https://medium.com/@salonimalhotra1ind/how-to-increment-a-number-value-in-mongoose-785066ba09d8
我的问题是我想增加默认的 0 值,但由于某种原因,当我检查该值仍为 0 时。
这一定很简单,我尝试了几种不同的方法,但仍然没有计数。 非常感谢您对此事的任何想法! 谢谢!
这是带有“viewCount”的架构:
const {Schema, model} = require('mongoose');
const UrlSlugs = require('mongoose-url-slugs');
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
category: {
type: Schema.Types.ObjectId,
ref: 'categories'
},
title: {
type: String,
require: true
},
slug: {
type: String
},
status: {
type: String,
default: 'public'
},
allowComments: {
type: Boolean,
require: true
},
body: {
type: String,
require: true
},
file: {
type: String
},
date: {
type: Date,
default: Date.now()
},
dateToApply: {
type: Date
},
viewCount: {
type: Number,
default: 0
},
comments: [{
type: Schema.Types.ObjectId,
ref: 'comments'
}]
}, {usePushEach: true});
PostSchema.plugin(UrlSlugs('title', {field: 'slug'}));
try {
module.exports = model('posts', PostSchema);
} catch (e) {
module.exports = model('posts');
}
以及使用 $inc 指向帖子的路径:
router.get('/post/:slug',(req, res) => {
Post.findOneAndUpdate({slug : req.params.slug}, {$inc : {viewCount : 1}});
Post.findOne({slug: req.params.slug})
.populate({path: 'comments', populate: {path: 'user', model: 'users'}})
.populate('user')
.then(post => {
return Category.find({})
.then(categories => {
res.render('home/post', {post: post, categories: categories});
});
});
});
【问题讨论】:
标签: node.js database mongodb mongoose increment