2017-11-11 129 views
-1

我想了解MongoDB是如何工作的。 我創建了一個本地的MongoDB有以下集合:貓鼬連接現有的數據庫

db.user.find().pretty() 
{ 
    "_id" : ObjectId("5a05844833a9b3552ce5cfec"), 
    "firstname" : "Emanuel", 
    "lastname" : "Mars", 
    "username" : "mae", 
    "email" : "[email protected]", 
    "passwort" : "mae", 
    "role" : 1 
} 

現在我想連接到這個數據庫與表達。 連接有效,但我沒有收到任何數據。 這是我創建的模型:

var userSchema = new mongoose.Schema({ 
    firstname: { type: String }, 
    lastname: { type: String }, 
    username: { type: String }, 
    email: { type: String }, 
    passwort: { type: String }, 
    role: { type: Number } 
}, { collection : 'user' }); 

module.exports = mongoose.model('user', userSchema); 

這是我多麼希望得到所有用戶在收集用戶:

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

User.find({}, function (err, user) { 
console.log('yes', user); 
}); 

在它應該處理的登錄過程從用戶端MongoDB的。

已解決: 我忘了在連接URL的末尾添加數據庫名稱。

+0

@Dij輸出是一個空數組 – emma93

+0

@Dij是,db.once( '開放式',()=> { 的console.log(」 DB連接'); });是正確的 – emma93

回答

0
//server.js 
var configDB = require('./config/database.js'); 

mongoose.connect(configDB.url); 
const db = mongoose.connection; 

db.on('error',() => { 
    console.log('DB connection Error'); 
}); 
db.once('open',() => { 
    console.log('DB is connected'); 
}); 

require('./config/passport')(passport); 

//user.js

const mongoose = require('mongoose'); 
const bcrypt = require('bcrypt-nodejs'); 

var userSchema = new mongoose.Schema({ 
    firstname: { type: String }, 
    lastname: { type: String }, 
    username: { type: String }, 
    email: { type: String }, 
    passwort: { type: String }, 
    role: { type: Number } 
}, { collection : 'user' }); 


userSchema.methods.generateHash = function(password) { 
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); 
}; 

userSchema.methods.validPassword = function(password) { 
    return bcrypt.compareSync(password, this.local.password); 
}; 

module.exports = mongoose.model('user', userSchema); 
+4

即使它是你自己的問題的答案,請嘗試廣告一些解釋,以使其對其他用戶有用。 – IvanH