所以我有一个Mongo模式如下;
const mongoose = require('mongoose');
const adressSchema = require('./entities/adress.entities');
const cardSchema = require('./entities/card.entities');
const UserSchema = mongoose.Schema ({
id: {
type: String,
},
username: {
type: String,
required: true
},
address: {
type: adressSchema,
required: true
},
creditCards: [cardSchema],
email: {
type: String,
required: true,
lowercase: true,
validate: {
validator: function (v) {
return v.length>1 && /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(v);
},
message: props => `${props.value} is not a valid email!`
},
phone : {
type: mongoose.Schema.Types.String,
required: true,
validate: {
validator: function (v) {
return v.length > 1 && /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/.test(v);
},
message: props => `${props.value} is not a valid phone number!`
},
},
shippingAddress:[adressSchema],
role: {
type: mongoose.Schema.Types.String,
enum: ['admin', 'user','owner'],
default: 'user',
required: true
},
password: {
type: String,
required: true
},
lastLogin: {
type: Date,
},
status: {
type: String,
enum: ['active', 'blocked', 'deleted'],
default: 'active',
required: true
},
image: String,
},
},{timestamps: true});
/* -------------------------------- pre save -------------------------------- */
UserSchema.pre('save', function (next) {
if (this.isNew) {
this.status = 'active';
this.role = 'user';
}
next();
});
/* ------------------------ create user token object ------------------------ */
UserSchema.virtual('token').get(function () {
return {
id: this.id,
role: this.role,
};
});
module.exports= mongoose.model('Users', UserSchema);
字符串
下面是我的用户服务和控制器
服务
const UserSchema = require('./users.schema');
module.exports = {
creatUser: async (data) => {
try {
var user = await UserSchema.create({
username: data.username,
email: data.email,
password: data.password,
phone: data.phone,
image: data.image,
address: data.address,
role: data.role??'user',
status: data.status??'active',
shippingAddress: data.shippingAddress??[],
creditCards: data.creditCards??[],
lastLogin: data.lastLogin??new Date(),
});
return user;
} catch (error) {
throw error;
}
},
getUser: async (id) => {
try {
const user = await UserSchema.findById(id);
return user;
} catch (error) {
throw error;
}
},
updateUser: async (id, user) => {
try {
const updatedUser = await UserSchema.findByIdAndUpdate(id, user, { new: true });
return updatedUser;
} catch (error) {
throw error;
}
},
login: async (email) => {
try {
const user = await UserSchema.findOne({ email });
return user;
} catch (error) {
throw error;
}
},
getUsers: async () => {
try {
const users = await UserSchema.find();
return users;
} catch (error) {
throw error;
}
},
}
型
控制器
const userServices = require('./users.service');
const response = require('../../utils/responseHandler.util');
const authMiddleware = require('../../middleware/authentication.middleware');
module.exports ={
register: async (req, res) => {
try {
const data = req.body;
data.password = authMiddleware.hashPassword(data.password);
var user = await userServices.creatUser(data);
if(user){
user.id = user._id.toString();
await user.save();
return response.sendData(res, user);
}else{
return response.sendError(res, {message:'Error while creating user'});
}
} catch (error) {
return response.sendError(res, error);
}
},
login: async (req, res) => {
try {
const {email, password} = req.body;
const user = await userServices.login(email);
if(user){
const isMatch = authMiddleware.comparePassword(password, user.password);
if(isMatch){
const token = authMiddleware.generateToken(user.toObject());
return response.sendData(res, {data: user, token: token},'Login successfull');
}else{
return response.sendError(res, {message:'Password not matched'});
}
}else{
return response.sendError(res, {message:'Email not found'});
}
} catch (error) {
return response.sendError(res, error);
}
},
getUsers: async (req, res) => {
try {
const users = await userServices.getUsers();
return response.sendData(res, users);
} catch (error) {
return response.sendError(res, error);
}
},
getUser: async (req, res) => {
try {
const id = req.params.id;
const user = await userServices.getUser(id);
return response.sendData(res, user);
} catch (error) {
return response.sendError(res, error);
}
},
}
型
下面是我使用Rest Extension发送的请求Request
POST http://localhost:5000/api/register
Content-Type: application/json
{
"username": "Test User",
"email": "[email protected]",
"phone": "+23324812548",
"password": "124586",
"address": {"address": "Eben Fashion","city": "Kumasi","country": "Ghana","zipCode": "00233"}
}
型
这是我得到的回应回应
{
"success": true,
"message": "Success",
"data": {
"username": "Test User",
"address": {
},
"creditCards": [],
"email": "[email protected]",
"_id": "65609dce1d69960f898c9716",
"createdAt": "2023-11-24T12:57:50.482Z",
"updatedAt": "2023-11-24T12:57:50.512Z",
"__v": 0,
"id": "65609dce1d69960f898c9716"
}
}
型
很明显,你可以看到密码和电话字段没有被发布,即使它们是从请求发送的。其他字段,如状态和角色也没有被发布,即使它们有默认值。
**附加信息:**mongoose:“^8.0.1”节点v18.18.2
bbx是来自mongodb数据库的图片; x1c 0d1x
我尝试使用UserSchema.create(data)代替.create({}),但仍然不起作用
1条答案
按热度按时间jljoyd4f1#
这听起来可能很有趣,但我注意到电子邮件验证的花括号将其余字段括起来。