【发布时间】:2019-08-10 16:09:16
【问题描述】:
这快把我逼疯了。 Express 路由器适用于 Mongoose 模型,但我无法在没有路由的其他文件中使用模型。每次我尝试使用导入的模型或猫鼬模式运行文件时,它都会在控制台中返回空白。我在用户路由器文件中以完全相同的方式调用该函数。
///////////////////////////////
//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);
}
编辑:我发现这篇文章似乎它可能是猫鼬本身的设置。有关如何解决此问题的任何想法?
How can I interact with MongoDB via Mongoose without Express?
【问题讨论】:
-
能否分享一下你的user.js代码
-
这有什么更新吗?
标签: javascript node.js mongodb mongoose