【发布时间】:2019-08-16 08:47:42
【问题描述】:
我使用 NodeJS / Mongoose 创建了一个 CRUD,以 MVC 样式拆分文件。在下面显示的路由示例中,当执行retrieveOne 例程时,有必要等待其处理,然后将用户重定向到一个或另一个路由。我想使用 Bluebird 等待处理。我需要一些帮助来实施例程。
Index.js ----------------------------- ---
const myCRUD = require('./api/controllers/controller')
router.post('/login', function(req, res, next) {
// HOW TO IMPLEMENT BLUEBIRD HERE?
// How to wait for the "retrieveOne" process and a then do a "if" test (below)?
let ret = myCRUD.retrieveOne({ name: "abc test" });
if(!ret) {
res.redirect('/success')
} else {
res.redirect('/error')
}
})
controller.js ------------------------------------------
const mongoose = require('mongoose');
const Schema = require('./schema-user');
const Model = mongoose.model('users', Schema);
const CRUD = {
retrieveOne: function(query) {
Model.findOne(query, function(err, result) {
if (err) return err;
return result;
});
}
}
module.exports = CRUD;
注意:我已经在 S.O. 中找到了几个使用和不使用 Bluebird 的示例,但我无法让它工作: 示例:1、2、3、4、5
【问题讨论】:
-
顺便说一句,您传递给retrieveOne 的查询看起来有点不稳定。那是错字吗?它应该更像:
myCRUD.retrieveOne({ name: "abc test"}); -
是的,你是对的。这是一个错字。我已经解决了。
标签: javascript node.js mongoose bluebird