我在哪里定义猫鼬模式的功能
Where do i define function for mongoose schema
我只是问自己一个问题,即为猫鼬模式定义函数的正确方法是什么。
以我的UserSchema
为例。在我的许多路线中,我想获取用户的信息,以便我进行查询 getUserByUsername
其中包括 findOne(username: username)
.
正如我所写,我在很多路线上都这样做。因此,为了缩短我的代码,我希望只使用一次此功能,而不是一次又一次地在每条路线中使用。我想要一个中心位置,我可以随时调用此函数。
所以我开始搜索并发现,直接在我的 user.js
中添加函数是有效的,这是我的 UserSchema 定义。
整个文件如下所示:
user.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);
}
但我现在想知道,这是存储函数的正确方法还是有更好的/其他方法?
您应该创建一个控制器文件夹,您将在其中定义函数,这些函数将在路由 class 中调用,任何 request.You 可以在下面的文章中有详细的想法。
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes
我只是问自己一个问题,即为猫鼬模式定义函数的正确方法是什么。
以我的UserSchema
为例。在我的许多路线中,我想获取用户的信息,以便我进行查询 getUserByUsername
其中包括 findOne(username: username)
.
正如我所写,我在很多路线上都这样做。因此,为了缩短我的代码,我希望只使用一次此功能,而不是一次又一次地在每条路线中使用。我想要一个中心位置,我可以随时调用此函数。
所以我开始搜索并发现,直接在我的 user.js
中添加函数是有效的,这是我的 UserSchema 定义。
整个文件如下所示:
user.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);
}
但我现在想知道,这是存储函数的正确方法还是有更好的/其他方法?
您应该创建一个控制器文件夹,您将在其中定义函数,这些函数将在路由 class 中调用,任何 request.You 可以在下面的文章中有详细的想法。
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes