【问题标题】:How to increment value in mongodb with node js [duplicate]如何使用节点 js 在 mongodb 中增加值 [重复]
【发布时间】:2019-07-28 21:04:45
【问题描述】:

我想知道访问者的数量。所以我刚刚创建了一个带有计数的集合

 var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Visitor = new Schema({
    count: { type: Number, default: 0 },
});
module.exports = mongoose.model('visitor', Visitor);

现在我想增加路由 /backend/visitors 正在调用的计数值

const Visitor = require('../models/Visitor');
router.route('/backend/visitors').get(function (req, res, next) {
    const visitor = new Visitor({
        count:1,
    });
    Visitor.update({}, { __v: 0 })
        .then(users => {
            console.log(users)
            try {
                visitor
                    .save()
                    .then(visitor => {
                        res.send(visitor);
                    })
            }
        }
    )
});

我不知道如何增加数据库中的计数值,之后我想向页面发送计数响应,例如res.send(count)

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    $inc 运算符用于递增或递减(使用减号)操作。

    更新操作查询,请先参考MongoDB文档:https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/index.html

    如果访客模式只有一个文档,您应该使用findOneAndUpdate 查询。 您的查询将如下所示:

    Visitor.findOneAndUpdate({}, {
      $inc: { count: 1 }
    }).exec();
    

    如果有多个文档,应该使用updateMany查询:

    Visitor.updateMany(selectQueryObj, {
      $inc: { count: 1 }
    }).exec()
    

    【讨论】:

    • 谢谢先生,但它返回一个错误Unhandled rejection CastError: Cast to number failed for value "{ '$inc': 1 }" at path "count",你能帮我吗
    • 我已编辑查询。我在放置 $inc 运算符时出错
    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 2019-10-22
    • 2021-12-17
    • 2021-11-18
    • 2016-11-25
    相关资源
    最近更新 更多