Javascript Mongoose连接现有数据库
我想了解MongoDB是如何工作的。 我使用以下集合创建了一个本地MongoDB:Javascript Mongoose连接现有数据库,javascript,node.js,mongodb,express,Javascript,Node.js,Mongodb,Express,我想了解MongoDB是如何工作的。 我使用以下集合创建了一个本地MongoDB: db.user.find().pretty() { "_id" : ObjectId("5a05844833a9b3552ce5cfec"), "firstname" : "Emanuel", "lastname" : "Mars", "usernam
db.user.find().pretty()
{
"_id" : ObjectId("5a05844833a9b3552ce5cfec"),
"firstname" : "Emanuel",
"lastname" : "Mars",
"username" : "mae",
"email" : "myEmail@email.ch",
"passwort" : "mae",
"role" : 1
}
现在,我想用Express连接数据库。
连接正常,但我没有任何数据
这是我创建的模型:
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的末尾添加DB名称
//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);
@Dij输出为空array@Dij是,db.once('open',()=>{console.log('db is connected');});是正确的,即使这是对您自己问题的回答,请尝试做一些解释,使其对其他用户有用。