簡體   English   中英

dropCollection不會刪除集合

[英]dropCollection isn't dropping the collection

貓鼬4.0.3
節點0.10.22
mongod db版本3.0.1

我正在嘗試使用Moongoose刪除收藏集,但無法正常工作

run: function() {
    return Q(mongoose.connect('mongodb://127.0.0.1:27017/test',opts))
    .then(function(data){
        return Q(mongoose.connection.db.dropCollection('departments'))
        .then(function(data2){
            console.log('data2 is ',data2);
            return Q(true);
        }).catch(function(err){
            console.log('err is',err);
            return Q(false);
        });
    }).catch(function(err){
        console.log('err is', err);
        return Q(false);
    });
}

這將返回data2 is undefined

我試圖根據以下問題回答答案: Mongoose.js:刪除集合或數據庫

我認為您誤解了貓鼬,db和Q交互的方式。

您可以嘗試(未經測試)

run: function() {
  return Q(mongoose.connect('mongodb://127.0.0.1:27017/test',opts).exec())
  .then(function(){
    var db = mongoose.connection.db;
    var drop = Q.nbind(db.dropCollection, db);
    return drop('departments')
           .then(function(data2){
             console.log('data2 is ',data2);
             return true;
            }).catch(function(err){
             console.log('err is',err);
             return false;
             });
}).catch(function(err){
    console.log('err is', err);
    return false;
});

}

為了返回Promise,需要使用exec()調用貓鼬函數。

據我所知,這還沒有擴展到dropCollection方法,因此您需要對其進行去節點化。

我認為您不能以這種方式使用Q。

Q()將您傳遞給它的任何東西變成一個承諾。 當您以自己的方式傳遞函數調用時,實際上就是傳遞了該函數的返回值。 換句話說,就像Q(3)可以解析為3Q(nodefunc(args))可以解析為nodefunc(args)返回的任何值-在異步函數不是特別多的情況下。

我想您想改用ninvoke (aka nsend )。

Q.ninvoke(對象,方法名,...參數)

別名: Q.nsend

使用給定的可變參數調用Node.js風格的方法,返回一個諾言,如果該方法返回一個結果,則該諾言將被滿足;如果該方法返回一個錯誤(或同時引發一個錯誤),則將被拒絕。

貓鼬API文檔說, connect是一個同步方法,不返回任何內容。 它的近親createConnection將返回一個連接對象,並且可能更適合該用例。

以下代碼同時具有-調用Q的同步方法返回實際值,以及調用Q.nsend的異步方法與回調一起使用。

run: function() {
    return Q(mongoose.createConnection('mongodb://127.0.0.1:27017/test', opts))
    .then(function(connection){
        return Q.nsend(connection.db, 'dropCollection', 'departments')
        .then(function(data){
            console.log('data is ', data);
            return data;
        });
    }).catch(function(err){
        console.log('err is', err);
    });
}

(未經測試的代碼)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM