我正在使用promise并发送响应但是在.then()函数中我无法使用res.send()发送响应;
我的代码是
var express = require ('express'); //EXPRESS Package
var bodyParser = require('body-parser');// get body-parser
var route = express.Router(); //define our app using express
var multer = require('multer');
var validator = require('validator');
var userModel = require('../../model/user.model');
var session = require('express-session');
route.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
route.use(bodyParser.json()); // for parsing application/json
// route.use(bodyParser.json({ type: 'application/vnd.api+json' }))
route.put("/personal/:id", function (req, res) {
data = {};
data['personal_details'] = req.body;
return userModel.update(req.params.id, data).then( function (result) {
// console.lssog(result);
res.send();
}).catch( function ( err ){
res.send(err).status(400);
});
});
// route.put("/contact/:id", function (req, res) {
// userModel.update(req.params.id, "contact_details", req.body).then( function () {
// res.sendStatus(200)
// }).catch( function ( err ){
// res.send(err).status(400);
// });
// });
module.exports = route;
用户模型文件是user.model.js,如下所示:
var passwordHash = require('password-hash');
var mongo = require('mongoskin');
var Q = require('q');
var _ = require('lodash');
var randomstring = require('randomstring');
var db = mongo.db('mongodb://127.0.0.1/angulardemo');
db.bind('demotest');
// var hash = bcrypt.hashSync("12345", salt);
var model = {};
model.login = login;
model.create = create;
model.update = update;
model.destroy = destroy;
model.edit = edit;
module.exports = model;
/**
* Create new user
* @param {request data} userData
*/
function create (userData){
var deferred = Q.defer();
db.demotest.findOne({"email" : userData.email}, function (err, user) {
if (err) deferred.reject(err);
if(user){
deferred.reject('Email "' + userData.email + '" is already taken');
}
else{
createUser();
}
});
function createUser() {
var user = _.omit(userData, ['password', 'c_password']);
var hashedPassword = passwordHash.generate(userData.password);
user.password = hashedPassword;
user.api_token = randomstring.generate(50);
user.registration_code = randomstring.generate(10);
user.is_active = 1;
user.is_verified = 1;
db.demotest.insert(user, function (err, doc) {
if (err) deferred.reject(err);
deferred.resolve();
});
}
return deferred.promise;
}
/**
* Login user
* @param {user request data} data
*/
function login(data) {
var deferred = Q.defer();
db.demotest.findOne({"email" : data.email}, function (err, user) {
if (err) deferred.reject(err);
if(!user) deferred.reject("User not found");
if(user && passwordHash.verify(data.password, user.password)){
deferred.resolve(user);
}
else{
deferred.reject("Invalid Credential");
}
});
return deferred.promise;
}
/**
* Update User
* @param {user id} id
* @param {user data} data
*/
function update(id, data){
var deferred = Q.defer();
// validation
db.demotest.findById(id, function (err, user) {
if (err) deferred.reject(err);
if (user.id !== id) {
// username has changed so check if the new username is already taken
db.demotest.findOne(
{ _id: id },
function (err, user) {
if (err) deferred.reject(err);
if (user) {
// username already exists
deferred.reject('User "' + user.username + '" is already taken')
} else {
updateUser();
}
});
} else {
updateUser();
}
});
function updateUser() {
db.demotest.update(
{ _id: mongo.helper.toObjectID(id) },
{ $set: data },
function (err, doc) {
if (err) deferred.reject(err);
deferred.reject("err");
});
}
return deferred.promise;
// var deferred = Q.defer();
// db.demotest.update({_id : mongo.helper.toObjectID(id)}, {$set: data}, function (err, result) {
// console.log(result);
// if (err) deferred.reject(err);
// deferred.resolve("OLLLL");
// });
// return deferred.promise;
}
function destroy() {
}
function edit() {
}
// var insertTestDoc = function (db, callback) {
// //console.log("one"); return ;
// var collection = db.collection('demotest');
// collection.insertOne({"title" : "demotest", "description" : "Lorem Ipsum Sit Emet.", "password" : hash}, function ( err, db ){
// assert.equal(err, null);
// callback();
// });
// }
// var login = function (db, callback) {
// var collection = db.collection('demotest')
// var cursor = collection.findOne({"title" : "demotest"});
// console.log(cursor);
// // cursor.each(function(err, doc) {
// // assert.equal(err, null);
// // if (doc != null) {
// // console.log(doc);
// // } else {
// // callback();
// // }
// // });
// }
// MongoClient.connect('mongodb://localhost/angulardemo', function ( err, db ){
// assert.equal( null, err );
// console.log("Connected to the server correctly");
// login(db, function () {
// db.close();
// });
// // insertTestDoc(db, function () {
// // db.close();
// // });
// });
请协助谢谢
答案 0 :(得分:0)
我可以根据你所展示的内容考虑两种可能性,其中一种取决于你正在使用的猫鼬的版本。实际上,猫鼬的使用是我的假设,因为你从来没有提到它......
您越有可能永远不会真正连接到数据库。在您的代码中,某个地方需要调用mongoose.connect()
或mongoose.createConnection()
,这会在应用启动时触发(或者至少在请求挂起之前您已经看到)。
如果你实际上是这样做并且没有分享它,那么下一个最可能的事情是你在4.0之前使用mongoose版本,其中查询(例如{{1} })没有跟随Promise api,你跟.update()
打电话一样:
exec()
如果我对猫鼬的假设错了,或者我的建议都错了,请用相关信息更新您的问题。