복붙노트

[MONGODB] 합니까 몽구스는 MongoDB를`findAndModify` 방법을 지원합니까?

MONGODB

합니까 몽구스는 MongoDB를`findAndModify` 방법을 지원합니까?

나는 원자 몽구스를 사용하여 필드를 증가 findAndModify를 사용하고 싶습니다.

"개체 #있는 방법 'findAndModify을'이없는 형식 오류"그러나, 아래 코드는 오류가 발생합니다 :

// defining schema for the "counters" table
var tableSchema = new Schema({
    _id: String,
    next: Number        
});

// creating table object for the counters table
var counters_table = mongoose.model('counters', tableSchema);
var tableObj = new counters_table();    

// increment the "next" field on the table object
var query = {_id: 'messagetransaction'};
var update = {'$inc': {next: 1}};
var ret = tableObj.findAndModify(query, [], update, true, true, function(err) {
     if (err) { 
         throw err;
     }
     else { 
         console.log("updated!");
     }
});

해결법

  1. ==============================

    1.문서화,하지만 소스 코드를 읽은 후, 나는 다음과 같은 해결책을했다 :이 기능은 (전혀 읽기) 잘되지 않습니다.

    문서화,하지만 소스 코드를 읽은 후, 나는 다음과 같은 해결책을했다 :이 기능은 (전혀 읽기) 잘되지 않습니다.

    컬렉션의 스키마를 만듭니다.

    var Counters = new Schema({
      _id: String,
      next: Number     
    });
    

    모델의 수집의 findAndModify 방법을 노출됩니다 스키마에 대한 정적 메서드를 만듭니다.

    Counters.statics.findAndModify = function (query, sort, doc, options, callback) {
      return this.collection.findAndModify(query, sort, doc, options, callback);
    };
    

    모델을 만듭니다.

    var Counter = mongoose.model('counters', Counters);
    

    찾기 및 수정!

    Counter.findAndModify({ _id: 'messagetransaction' }, [], { $inc: { next: 1 } }, {}, function (err, counter) {
      if (err) throw err;
      console.log('updated, counter is ' + counter.next);
    });
    

    보너스

    Counters.statics.increment = function (counter, callback) {
      return this.collection.findAndModify({ _id: counter }, [], { $inc: { next: 1 } }, callback);
    };
    
    Counter.increment('messagetransaction', callback);
    
  2. ==============================

    2.이름이 약간 다릅니다하지만 이것은 완전히, 이제 몽구스 3.x를 지원됩니다.

    이름이 약간 다릅니다하지만 이것은 완전히, 이제 몽구스 3.x를 지원됩니다.

    http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

    http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

    http://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove

    http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove

  3. ==============================

    3.몽구스 3.x에 대한 제작 작업 버전 증가

    몽구스 3.x에 대한 제작 작업 버전 증가

    var mongoose = require('mongoose');
    
    var CounterSchema = new mongoose.Schema({
        _id: String,
        next: {type: Number, default: 1}
    });
    
    CounterSchema.statics.increment = function (counter, callback) {
        return this.findByIdAndUpdate(counter, { $inc: { next: 1 } }, {new: true, upsert: true, select: {next: 1}}, callback);
    };
    

    이런 식으로 뭔가를 사용 :

    Counter.increment('photo', function (err, result) {
        if (err) {
            console.error('Counter on photo save error: ' + err); return;
        }
        photo.cid = result.next;
        photo.save();
    });
    

    나는 누군가가 편리 희망

  4. ==============================

    4.버전 3에서는 몽구스 findOneAndUpdate 방법은 MongoDB의의 findAndModify 작업을 제공합니다. 그것은과 같이 작동합니다 :

    버전 3에서는 몽구스 findOneAndUpdate 방법은 MongoDB의의 findAndModify 작업을 제공합니다. 그것은과 같이 작동합니다 :

    var query = { name: 'Sprinkls' };
    var update = { name: 'Sprinkles' };
    var options = { new: false };
    Cat.findOneAndUpdate(query, update, options, function (err, cat) {
      if (err) ..
      render('cat', cat);
    });
    

    여기에 더 많은 정보 : http://aaronheckmann.tumblr.com/post/48943524629/mongoose-v3-part-2-findandmodify

  5. ==============================

    5.나는에 findAndModify있어

    나는에 findAndModify있어

    하나의 DB를 왕복에 다음 코드를 사용하여 :

    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);
      });
    }
    

    즐겨! - 쿠란

  6. ==============================

    6.답변을 많이하지만 난이 간단한 해결책을 찾을 수 있습니다.

    답변을 많이하지만 난이 간단한 해결책을 찾을 수 있습니다.

    Counter.findByIdAndUpdate(ID, {$inc: {next:1}}, function (err, data) {
    
    
    });
    
  7. ==============================

    7.@furf에서 위의 응답을 가지고가는 것은, 이쪽은 내 약속 솔루션입니다 :

    @furf에서 위의 응답을 가지고가는 것은, 이쪽은 내 약속 솔루션입니다 :

    // eslint-disable-next-line func-names
    localeTypesSchema.statics.findAndModify = function (query, sort, update, opts, callback) {
        const cb = callback || (() => { });
        try {
            const result = this.collection.findAndModify(query || {}, sort || [], update || {}, opts);
            cb(null, result);
            return Promise.resolve(result);
        } catch (err) {
            cb(err);
            return Promise.reject(err);
        }
    };
    
  8. ==============================

    8.나는 http://www.mongodb.org/display/DOCS/findAndModify+Command의 하단에 표시 직접 명령 스타일을 사용하는 것이 좋습니다 것입니다. 나는 명령을 실행하는 방법을 알 수 몽구스을 잘 알고 충분히 아니지만, 모든 드라이버는 그것을 할 수있는 방법을 제공합니다. 몽구스하지 않는 경우, 직접 http://www.mongodb.org/display/DOCS/Commands의 상단에 설명 된 스타일을 사용하여 그것을 할 수 있습니다.

    나는 http://www.mongodb.org/display/DOCS/findAndModify+Command의 하단에 표시 직접 명령 스타일을 사용하는 것이 좋습니다 것입니다. 나는 명령을 실행하는 방법을 알 수 몽구스을 잘 알고 충분히 아니지만, 모든 드라이버는 그것을 할 수있는 방법을 제공합니다. 몽구스하지 않는 경우, 직접 http://www.mongodb.org/display/DOCS/Commands의 상단에 설명 된 스타일을 사용하여 그것을 할 수 있습니다.

    즉, 당신이 정말 findAndModify이 필요하고 해당 업데이트는 당신이해야 할 일을하지 않을 것을 확인해야했다. 업데이트 http://www.mongodb.org/display/DOCS/Updating를 살펴 할 것을 참조하십시오.

  9. ==============================

    9.당신이 당신의 쿼리에서 OBJECTID를 사용하는 경우, MongoDB가이 문서를 찾을 수 없습니다 것을 furf 대답에 추가. 몽구스 층은 적절한 개체 ID에 라우팅 PARAMS에서 당신이 얻을 진수 문자열 객체 ID를 변환을 담당한다.

    당신이 당신의 쿼리에서 OBJECTID를 사용하는 경우, MongoDB가이 문서를 찾을 수 없습니다 것을 furf 대답에 추가. 몽구스 층은 적절한 개체 ID에 라우팅 PARAMS에서 당신이 얻을 진수 문자열 객체 ID를 변환을 담당한다.

    당신이해야 할이 문제를 해결하기 위해 :

    var ObjectID = require('mongodb').ObjectID;
    
    
    var itemId = req.params.itemId;
    var objectId = ObjectID.createFromHexString(itemId);
    Item.findAndModify({_id: objectId},
    
  10. from https://stackoverflow.com/questions/7334390/does-mongoose-support-the-mongodb-findandmodify-method by cc-by-sa and MIT license