我正在尝试将我的Google Cloud App Engine连接到mlab,它将在其中插入数据。在我的代码中,我正在使用moongoose。当我尝试插入我的值时,它给我
(node:16) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined
at /app/db/register.js:66:12
at $initialConnection.then.err (/app/node_modules/mongoose/lib/connection.js:556:14)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
这是我的register.js代码
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var LoginInfoSchema = new mongoose.Schema
({
email : String,
user: String,
password: String,
passwordConfirm : String,
passwordRetrieval : String
});
var User = mongoose.model('User',LoginInfoSchema);
router.post('/register', function(req, res) {
var validatorUser = {
email : req.body.email ,
user : req.body.user ,
password : req.body.password,
passwordConfirm : req.body.passwordConfirm,
passwordRetrieval : req.body.passwordRetrieval
};
var putUser = {
email : req.body.email ,
user : req.body.user ,
password : req.body.password,
passwordRetrieval : req.body.passwordRetrieval
};
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('user', 'username is required').notEmpty();
req.checkBody('password' , 'password is not empty').notEmpty();
req.checkBody('passwordConfirm' , 'paswword should be same').equals
(req.body.password);
req.checkBody('passwordRetrieval' , 'password retrieval key is not empty').notEmpty();
var errors = req.validationErrors();
if(errors){
res.redirect('/webrtc.js');
}
else{
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(putUser.password, salt, function(err, hash) {
putUser.password = hash;
});//end of hashing.
});//end of generating salt.
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(putUser.passwordRetrieval, salt, function(err, hash) {
putUser.passwordRetrieval = hash;
});//end of hashing.
});//end of generating salt.
mongoose.connect("mongodb://<username>:<password>@ds243212.mlab.com:43212/userinfo"
,{useNewUrlParser : true} ,function(err , db){
if(err) console.log(err);
db.collection("users").findOne({ email: {
"$regex": "^" + req.body.email + "\\b", "$options": "i"
}},function(er , mail){
if(mail)
{
console.log(mail);
res.redirect('/');
console.log('email already taken');
}
else
{
db.collection("users").insertOne(putUser, function(error, result) {
if(error) console.log(error);
//console.log(result);
console.log("1 document inserted");
});
res.redirect('/');
}// end of else part of check emai already taken
});
});//end of mongoose connection callback function
}//end of validation success.
});//end of post method register callback function
module.exports = router;
此代码在本地mongodatabase上运行良好,但是当我将其部署到Google云服务器上时,总是会出现错误。 请帮忙。