【问题标题】:Using $inc to increment a document property with Mongoose使用 $inc 来增加 Mongoose 的文档属性
【发布时间】:2012-01-27 03:52:23
【问题描述】:

我想在每次访问我的文档时将 views 计数增加 1。到目前为止,我的代码是:

Document
    .find({})
    .sort('date', -1)
    .limit(limit)
    .exec();

$inc 适合在这里的什么位置?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    从未使用过猫鼬,但快速查看文档here 似乎这对你有用:

    # create query conditions and update variables
    var conditions = { },
        update = { $inc: { views: 1 }};
    
    # update documents matching condition
    Model.update(conditions, update).limit(limit).sort('date', -1).exec();
    

    干杯,祝你好运!

    【讨论】:

      【解决方案2】:

      我遇到了另一个问题,它与 $inc.. 有点相关。所以我会在这里发布它,因为它可能会帮助其他人。我有以下代码:

      var Schema = require('models/schema.js');
      
      var exports = module.exports = {};
      
      exports.increase = function(id, key, amount, callback){
         Schema.findByIdAndUpdate(id, { $inc: { key: amount }}, function(err, data){
            //error handling
         }
      }
      

      来自不同的模块,我会称之为

      var saver = require('./saver.js');
      
      saver.increase('555f49f1f9e81ecaf14f4748', 'counter', 1, function(err,data){
          //error handling
      }
      

      但是,这不会增加所需的计数器。显然不允许直接将密钥传递给更新对象。这与对象字段名称中字符串文字的语法有关。解决方案是像这样定义更新对象:

      exports.increase = function(id, key, amount, callback){
      
         var update = {};
         update['$inc'] = {};
         update['$inc'][key] = amount;
      
         Schema.findByIdAndUpdate(id, update, function(err, data){
            //error handling
         }
      }
      

      【讨论】:

      • 您的代码的第一个版本中的错误是:{ $inc: { key: amount }}。您实际上并没有在那里使用key 变量,而是将对象键设为字符串"key"。编写此代码的正确方法是{ $inc: { [key]: amount }},使用ES2015 computed property keys
      【解决方案3】:

      为我工作(猫鼬 5.7)

      blogRouter.put("/:id", async (request, response) => {
      	try {
      		const updatedBlog = await Blog.findByIdAndUpdate(
      			request.params.id,
      			{
      				$inc: { likes: 1 }
      			},
      			{ new: true } //to return the new document
      		);
      		response.json(updatedBlog);
      	} catch (error) {
      		response.status(400).end();
      	}
      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-23
        • 1970-01-01
        • 1970-01-01
        • 2013-01-15
        • 2015-03-23
        • 1970-01-01
        • 2020-09-14
        • 1970-01-01
        相关资源
        最近更新 更多