Mongodb return old collection

后端 未结 3 2006
甜味超标
甜味超标 2021-01-24 13:05
router.post(\'/orders/finish\', function(req, res, next) {
var order_id = req.body.order_id;
var user_id  = req.body.user_id;
var table_id = \'\';

var result = [];



m         


        
相关标签:
3条回答
  • 2021-01-24 13:21

    You should wait for the update to complete before calling find

    db.collection('tables').update({id: table_id, status: true}, {$set: {status: false}}, function(err, result) {
            assert.equal(null, err);
            var cursorTables = db.collection('tables').find({status: false});
            cursorTables.forEach(function(doc, err) {
                assert.equal(null, err);
                resultTables.push(doc);
            }, function() {
                db.close();
            });
        });
    
    0 讨论(0)
  • 2021-01-24 13:28

    I recommend you use Async

    router.post('/', function(req, res) {
        var order_id = req.body.order_id;
        var user_id  = req.body.user_id;
        var table_id = '';
    
        mongo.connect(url, table_id, function(err, db) {
            myFuntion(db, table_id, function(result) {
                res.send(JSON.stringify(result)); // it should be what you need
            })
        })
    
    });
    
    function myFuntion(db, table_id, callback) {
        var result = [];
        async.waterfall([
            function(callback) {
    
                db.collection('tables').update({id: table_id, status: true}, {$set: {status: false}}, function(err, result) {
                    assert.equal(null, err);
                    callback(null);
                });
    
            }, function(callback) {
                db.collection('tables').find({status: false}, function(err, docs) {
                    docs.forEach(function(doc) {
                        result.push(doc);
                    })
                    callback(null, result);
                });
            }
        ], function(err, result) {
            callback(result);
        })
    
    }
    
    0 讨论(0)
  • 2021-01-24 13:31

    When you make your .find() call, your collection isn't done updating yet.

    You can choose to call .find() in the callback of your .update() call, or you could also use promises or async/await depending on your version.

    Another solution would be to use findAndModify with the new option:

    Optional. When true, returns the modified document rather than the original. The findAndModify() method ignores the new option for remove operations. The default is false.

    0 讨论(0)
提交回复
热议问题