This is driving me crazy. The Express router works fine with Mongoose models but I can't use the models in other files without routes. Every time I try running the file with the imported models or mongoose schema it returns blank in the console. I am calling the function exactly the same way in the user router file.
///////////////////////////////
//File: test.js (not working)//
///////////////////////////////
var user = require('./user');
user.getUserById({_id:'5c902f4c75d827057cc5ad17'}, function(err, user){
if(err) return console.error(err);
console.log(user);
});
////////////////////////////
//User model file: user.js//
////////////////////////////
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
var bcrypt = require('bcryptjs');
const moment = require('moment');
var UserSchema = new mongoose.Schema({
username: { type: String, required: true },
email: { type: String, required: true },
firstname: { type: String, required: true },
lastname: { type: String, required: true },
password: { type: String, required: true },
chargeApiId: { type: String, required: false },
address: { type: String, required: false },
state: { type: String, required: true },
county: { type: String, required: true },
businessname: { type: String, required: false },
updated_date: { type: String, default: moment(new Date()).format("DD/MM/YYYY HH:mm:ss") },
activated: {type: Boolean, required: false},
active_sub: {type: String, required: false},
lastlogin: { type: String, required: false },
datecreated: { type: String, required: true }
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
module.exports.test = function(id, callback) {
console.log('test');
User.findById(id, callback);
}
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback) {
const query = {username: username};
User.findOne(query, callback);
}
// Method to compare password for login
module.exports.comparePassword = function (candidatePassword, res, callback) {
bcrypt.compare(candidatePassword, res, (err, isMatch) => {
if (err) { return callback(err); }
callback(null, isMatch);
});
};
//password hashing
module.exports.bcyprtPw = function (password) {
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(password, salt);
console.log(hash);
return(hash);
}
Edit: I found this article an it seems it may be a setting in mongoose itself. Any ideas of how to do fix this?
How can I interact with MongoDB via Mongoose without Express?