【问题标题】:Saving and increment data to MongoDB with $inc使用 $inc 将数据保存和递增到 MongoDB
【发布时间】: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


    【解决方案1】:

    问题似乎是因为findOneAndUpdate 是一个异步函数,这意味着您对findOne 的下一次调用将在更新完成之前运行。

    您需要在您的findOneAndUpdate 呼叫之后呼叫.then(() => Post.findOne(... 以等待结果,或者更好的是只需在findOneAndUpdate 上使用{new: true} 标志,如下所示:

    router.get('/post/:slug',(req, res) => {
        Post.findOneAndUpdate({slug : req.params.slug}, {$inc : {viewCount : 1}}, {new: true})
            .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});
                    });
            });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 1970-01-01
      • 2023-03-30
      • 2017-05-12
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 2017-07-27
      相关资源
      最近更新 更多