Mongoose 4.0.3
Node 0.10.22
mongod 数据库版本 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未定义
我尝试遵循基于此问题的答案:Mongoose.js: remove collection or DB
最佳答案
我认为你不能这样使用 Q。
Q()
将您传递给它的任何内容转换为 promise 。当您按照您的方式传递函数调用时,您实际上传递了该函数的返回值。换句话说,就像 Q(3)
将解析为 3
一样,Q(nodefunc(args))
将解析为任何 nodefunc(args)
返回 - 对于异步函数,返回的值并不是特别多。
我想您想使用ninvoke
(又名nsend
)。
Q.ninvoke(object, methodName, ...args)
Alias:
Q.nsend
Calls a Node.js-style method with the given variadic arguments, returning a promise that is fulfilled if the method calls back with a result, or rejected if it calls back with an error (or throws one synchronously).
mongoose 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);
});
}
(未经测试的代码)
关于javascript - dropCollection 不会删除集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30625663/