2016-05-21 80 views
2

有人可以告訴我爲什麼這個承諾安裝不起作用。它應該刪除文檔,然後添加它然後找到它然後控制它。這不是安慰數據。使用承諾與貓鼬的麻煩

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(res){ 
     console.log("removed") 
     return Comp.remove({}).exec() 
    }) 
    .then(function(){ 
     return Comp.create(arr).exec() 
    }) 

    .then(function(data){ 
     return Comp.find({}).exec(); 
    }) 
    .then(function(data){ 
     console.log(data) 
    }) 

編輯:

捕獲的錯誤

[TypeError: Comp.create(...).exec is not a function]

回答

2

Model.create返回一個承諾,所以沒有必要調用.exec()的返回值。

.then(function(){ 
    return Comp.create(arr); 
}) 
+0

很酷。所以查詢不會返回一個承諾,但如果你使用'exec'的話。但'create'和'save'則返回一個promise,所以你不應該使用'exec'。對? –

+0

@jackblank沒錯。如有疑問,請查看Mongoose的[API文檔](http://mongoosejs.com/docs/api.html)。 – JohnnyHK