我只是问自己一个问题,什么是为mongoose模式定义函数的正确方法。
UserSchema
例如。在我的许多路线中,我希望获得用户的信息,以便进行查询
getUserByUsername
其中包括
findOne(username: username)
.
正如我写的,我在很多方面都是这样做的。所以为了缩短我的代码,我希望这个函数只使用一次,而不是一次又一次地出现在每个路径中。我想要一个中心位置,我可以随时调用这个函数。
user.js
这是我的UserSchema定义。
用户.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
const Partner = require('./partner');
const UserRights = require('./userRights');
//User Schema - Datenbankaufbau
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
partnerId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Partner'
},
userRights: {
type: mongoose.Schema.Types.ObjectId,
ref: 'UserRights'
},
isLoggedIn: {
type: Boolean,
default: false
},
hasToRelog: {
type: Boolean,
default: false
}
});
const User = module.exports = mongoose.model('User', UserSchema);
// Find User by ID
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
// Find User by Username
module.exports.getUserByUsername = function(username, callback) {
const query = {username: username};
User.findOne(query, callback);
}
但我现在想知道,这是存储函数的正确方法还是有更好的方法?