2017-07-17 72 views
2

我在學習貓鼬,我正在發一個簡單的post請求來將用戶添加到我的mongolab測試數據庫中。我使用的是基本的用戶模式,但是當我運行save()方法有時我得到一個mongoose.save()有兩種類型的行爲

Unhandled promise rejection (rejection id: 1): Error: data and salt arguments required

,有時什麼也沒有發生,應用程序只是什麼都不做。我使用Postman來測試發佈請求。

編輯:作爲MIKEY建議我刪除了決心,拒絕回調和處理.save()回調裏面的一切,但現在我得到以下錯誤:

(node:10964) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http:// mongoosejs.com/docs/promises.html

var express = require('express'); 
var morgan = require('morgan'); 
var mongoose = require('mongoose'); 
var bodyParser = require("body-parser"); 

var mPromise = require("mpromise"); 

var User = require('./models/user'); 

var app = express(); 


mongoose.connect('mongodb://root2:[email protected]:61742/ecommerce', function (err) { 
    if (err) console.log(err); 

    console.log("Connected to the database"); 
}); 

app.use(morgan('dev')); 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 

app.post("/create-user", function (req, res, next) { 

    var user = new User(); 

    user.profile.name = req.body.name; 
    user.password = req.body.password; 
    user.email = req.body.email; 

    user.save(function (err, user) { 
     if (err) { 
      res.send("deu erro"); 
     } else { 
      console.log("Deu bom"); 
      res.send("deu bom"); 
     } 
    }) 
}) 


app.get("/get-users", function (req, res, next) { 
    User.find({}) 
     .exec(function (err, users) { 
      if (err) res.send("Erro na hora de pegar os usuarios " + err); 
      res.send(users); 
     }); 
}); 



app.get('/', function (req, res) { 
    res.send("Deu mais bom"); 
}); 



app.listen(80, function (err) { 
    if (err) throw err; 
    console.log("Server is running on port 80"); 
}); 

此外,當我連接到mongolab我得到警告:

DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using conn ect() or createConnection() . See http://mongoosejs.com/docs/connections.html#use-mongo-client Server is running on port 80 Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

但因爲我不使用默認的MongoDB的lib我沒有用我的代碼進行任何的open()方法郭寶宏。我能夠將一個集合添加到mongolab數據庫中,但數據不完整,現在我正在爲此苦苦掙扎。

EDIT2:這是我UserSchema的使用bcrypt代碼:

var mongoose = require('mongoose'); 
var bcrypt = require('bcrypt'); 
var Schema = mongoose.Schema; 

/* The user schema attributes/fields */ 
var UserSchema = new Schema ({ 
    email : String, 
    password: String, 




    profile: { 
     name: {type: String, default: "Sem nome"}, 
     picture: {type: String, default: ''} 
    }, 

    address: String, 
    history: [{ 
     date: Date, 
     paid: {type: Number, default: 0}, 
     //item: { type: Schema.Types.ObjectId, ref: ''} 
    }] 
}); 

/* The method to hash the password before saving it to the database */ 

UserSchema.pre('save', function(next){ 
    var user = this; 
    if(!user.isModified('password')) return next(); 

    bcrypt.genSalt(10, function(err, salt){ 
     if(err) return next(err); 

     bcrypt.hash(user.password, salt, null, function(err, hash){ 
      if(err) return next(err); 
      user.password = hash; 
      next(); 
     }); 
    }); 
}); 


/* Compare the password between the database and the input from the user */ 

UserSchema.methods.comparePasswords = function(inputpassword){ 
    return bcrypt.compareSync(inputpassword, this.password); 
} 


module.exports = mongoose.model('User', UserSchema); 

任何幫助表示讚賞,感謝

+2

使用'then'和'catch'用'save'顯得那麼多餘。只需處理回調中的所有內容。 – Mikey

+0

@Mikey ok,但即使有或沒有解析和拒絕調用,代碼也不會響應任何內容。我仍然得到「未處理的承諾拒絕(拒絕ID:1):錯誤:數據和鹽參數要求」 –

+1

你的用戶模式是什麼樣的?我猜你正在使用一個庫來散列密碼,而不是提供正確的信息(即數據和鹽)。 – Paul

回答

0

除非我錯了,bcrypt.hash()接受3個參數不是4。因此,它的回調可能永遠不會被解僱。

應該是簡單

bcrypt.hash(user.password, salt, function (err, hash){ 
    if(err) return next(err); 
    user.password = hash; 
    next(); 
}); 

您可能還需要檢查user.password and salt are defined

+0

我絕對會像一個完整的douchebag現在。我在添加回調之前添加了null,因爲我遵循了Udemy課程。我在創建回調後忘記清除空值。那麼它發生了,非常感謝 –

1

要解決的第一個警告,對於mpromise,您可以使用本機Promise(節點版本> = 6)這樣做:

mongoose.Promise = global.Promise; 

解決您r第二警告,你必須使用useMongoClientdocumentation提出一個承諾的方法:

function connectDatabase(databaseUri) { 
    var promise = mongoose.connect(databaseUri, { 
     useMongoClient: true, 
    }); 

    return promise; 
} 

connectDatabase('mongodb://root2:[email protected]:61742/ecommerce') 
    .then(() => console.log("Connected to the database");) 
    .catch((err) => console.log(err)); 
0

下面的代碼可以解決你所有的問題

var mongoose = require('mongoose'); 
    var options = { 
     useMongoClient:true 
    }; 
    var dbUrl = 'mongodb://root2:[email protected]:61742/ecommerce'; 

    mongoose.connect(dbUrl,options); 
    mongoose.Promise = global.Promise; 
+0

,當我嘗試連接到mongoLab服務器時,它刪除了警告,非常感謝你 –