节点路线:
exports.addUser = async ( req, res, next ) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const unique = await User.isUserUnique( email );
console.log( unique );
bcrypt.hash( password, 10, function ( err, hash ) {
const user = new User( name, email, hash );
//user.saveUser();
} );
res.send( req.body );
};
型号:
const client = require( "../database/index" );
class User {
constructor( name, email, password ) {
this.name = name;
this.email = email;
this.password = password;
}
static isUserUnique( email ) {
return client.connect( () => {
return client.db( "alliance" ).collection( "users" ).findOne( { email } ).then( ( user ) => {
return user;
} );
} );
}
数据库:
const MongoClient = require( "mongodb" ).MongoClient;
const client = new MongoClient( url );
client.connect( function ( err ) {
if ( err ) {
console.log( err );
}
console.log( "Connected successfully to server" );
} );
module.exports = client;
为什么在节点路由中声明的唯一常量未定义? 它与“ return client.connect(())”有关吗? 基本上,我希望static方法可以返回用户,因此我假设您在Static方法内部要做的就是返回每个值,以便它们升至调用它的父级,然后在被调用的常量上获取它。我做了一些类似的事情,除了这次是用connect方法作为周围的父母。