Mongoose
Posted: Fri Feb 28, 2014 11:11 pm
Anyone use it with Mongodb and Nodejs? Alternatives?
Code: Select all
var bcrypt = require('bcryptjs');
var notEmtpy = function(val) {
return val && val.length;
};
module.exports = function(mongoose) {
var User = {
name: 'User',
schema: mongoose.Schema({
email: String,
password: { type: String, set: function(pwd) { // encrypt password
var salt = bcrypt.genSaltSync(10); // generate salt
return bcrypt.hashSync(pwd, salt); // encrypt against salt
}},
created: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now },
last_ip: String, // last log in IP, used to check against remember me cookie
current_ip: String, // current log in IP, used to check against remember me
active: { type: Boolean, default: true },
reset_password_token: String,
reset_sent_at: Date
})
};
// instance methods
User.schema.methods = {
passwordMatches: function(pwd) {
return bcrypt.compareSync(pwd, this.password);
}
};
// lifecycle callbacks
User.schema.pre('save', true, function(next, done) {
console.log('User trying to be saved!');
next();
//done(); // that 'true' flag in the pre callback makes it so that the user will not save until all of the lifecycle callbacks have passed done();
// mine is currently commented out so that I don't accidentally save any user records while testing
});
// validation
User.schema.path('email').validate(function(val, fn) {
fn(notEmtpy(val));
}, 'Email cannot be blank.');
User.schema.path('email').validate(function(val, fn) {
// Check only when it is a new user or when email field is modified
if (this.isNew || this.isModified('email')) {
var User = mongoose.model('User');
User.find({ email: val }).exec(function (err, users) {
fn(!err && users.length === 0);
});
} else {
fn(true);
}
}, 'Email already exists.');
User.schema.path('password').validate(function(val, fn) {
fn(notEmtpy(val));
}, 'Password cannot be blank.');
return User;
};Code: Select all
var fs = require('fs'),
path = require('path'),
Mongoose = require('mongoose'),
lodash = require('lodash'),
mongoose = Mongoose.connect('mongodb://' + config.db.host), // config in my case is a global variable where I can pass environment
db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
})
.forEach(function(file) {
var model = require(path.join(__dirname, file))(mongoose);
db[model.name] = mongoose.model(model.name, model.schema);
});
module.exports = lodash.extend({
mongoose: mongoose,
Mongoose: Mongoose
}, db);Code: Select all
var db = require('./models'),
mongoose = db.mongoose.connection; //load up the DB
// access models with db.User
// for example:
app.post('/sign_in', function(req, res, next) {
db.User.findOne({ 'email': req.param('email') }, function(err, user) {
if (err) {
throw err;
} else if (typeof user == 'undefined' || user === null) {
req.session.errors = { err: "The email or password you entered is incorrect." };
res.redirect(req.headers['referer']); // this plays into my flash messages in my case
} else {
// check password
// logged in, redirect to appropriate page, or do whatever else
}
});
});
//handle mongo errors
mongoose.on('error', console.error.bind(console, 'Mongo Connection Error: '));
//once the mongo connection is open, start the HTTP server
mongoose.once('open', function() {
http.createServer(app).listen(app.get('port'), function() {
// server running!
});
});Seriously check out Waterline. I think it is what you need. The schemas are very basic, and the querying is about as simple as it gets.hallsofvallhalla wrote:the code above is my point. Look at all that code you must write. I want simple query functions and that is it. Save data, pull data, done.
Not the black sheep but rather another valuable point of the conversations.