使用mongoose承诺排序文档

时间:2016-05-19 00:13:03

标签: javascript node.js mongodb promise

当我console.log(all)时,我希望找回已过滤的排序数据,但我会取回整个原始数据。为什么呢?

var Comp = require("./models/company.js");
  var arr = [
    {name : "comp1",industry : "industry1", ranking: 20},
    {name : "comp2",industry : "industry2", ranking: 5},
    {name : "comp3",industry : "industry3", ranking: 10}
  ]



var output = {};  
var promise = Comp.find({}).exec()
  promise.then(function(docs){
        return Comp.remove({}).exec()

    })
    promise.then(function(){
            console.log("deleted")
        })
    promise.then(function(){
        return Comp.create(arr).exec()

    })
    promise.then(function(data){
        output.data = data;
        console.log(output)
    })
    promise.then(function(){
        return Comp.find({}, 'name -_id ranking', {sort :{ranking :1}}).exec();
    })
    promise.then(
        function(all){
            console.log("test")
            console.log(all)
        },
        function(error){
            console.log(error)
        }
    )
    promise.then(function(){
        return Comp.count({}, function(count){
            return count;
        });
    })
    promise.then(function(count){
        console.log("count")
        // console.log(count)
    })

我的其他相关question

1 个答案:

答案 0 :(得分:2)

您将所有.then回调附加到同一承诺。这不是链接,而是branching

科:

var p = Promise.resolve(1);
p.then(foo);
p.then(bar); // wont wait for foo. Calls bar(1).

要链接,请始终附加到 last 承诺。

var p = Promise.resolve(1);
p = p.then(foo);
p = p.then(bar); // waits for foo. Calls bar(result_from_foo).

或简单地说:Promise.resolve().then(foo).then(bar);