Does Mongoose support the Mongodb `findAndModify` method?

前端 未结 9 2109
[愿得一人]
[愿得一人] 2020-11-29 23:57

I would like to use findAndModify to atomically increment a field, using Mongoose.

However, the code below throws the error \"TypeError: Object # has no method \'fin

相关标签:
9条回答
  • 2020-11-30 00:44

    a lot of answers but I find this simple solution.

    Counter.findByIdAndUpdate(ID, {$inc: {next:1}}, function (err, data) {
    
    
    });
    
    0 讨论(0)
  • 2020-11-30 00:44

    I got findAndModify to

    • Upsert a counter (create and initialize it if it doesn't exist)
    • Increment the counter
    • Call a callback with the incremented value

    in a single DB roundtrip using the following code:

    var Counters = new Schema({
      _id:String, // the schema name
      count: Number
    });
    
    Counters.statics.findAndModify = function (query, sort, doc, options, callback) {
        return this.collection.findAndModify(query, sort, doc, options, callback);
    };
    
    var Counter = mongoose.model('Counter', Counters);
    
    /**
     * Increments the counter associated with the given schema name.
     * @param {string} schemaName The name of the schema for which to
     *   increment the associated counter.
     * @param {function(err, count)} The callback called with the updated
     *   count (a Number).
     */
    function incrementCounter(schemaName, callback){
      Counter.findAndModify({ _id: schemaName }, [], 
        { $inc: { count: 1 } }, {"new":true, upsert:true}, function (err, result) {
          if (err)
            callback(err);
          else
            callback(null, result.count);
      });
    }
    

    Enjoy! - Curran

    0 讨论(0)
  • 2020-11-30 00:45

    just adding to furf answer that if you use objectId in your query, mongoDB will not be able to find your document. The mongoose layer takes care of converting the Hex string object id you get from the routing params to the proper object id.

    to solve this you need to:

    var ObjectID = require('mongodb').ObjectID;
    
    
    var itemId = req.params.itemId;
    var objectId = ObjectID.createFromHexString(itemId);
    Item.findAndModify({_id: objectId},
    
    0 讨论(0)
提交回复
热议问题