【发布时间】:2020-05-01 16:04:47
【问题描述】:
我正在使用猫鼬并有两个模型。 User 模型和 Service 模型,当用户登录时,该方法将 findOne() 用户(如果存在)或 create() 基于从 req.body 传入的新用户。
我的服务架构是这样的:
const serviceSchema = new mongoose.Schema({
name: {
type: String,
default: 'contentEditor'
},
display: {
type: String,
default: 'Content Editor'
},
accessLevel: {
type: Number,
min: 0,
max: 4,
default: 4
}
});
我的用户架构有点大,我删除了一些字段/值对,但我嵌入服务架构的部分如下所示:
const userSchema = new mongoose.Schema(
{
email: {
type: String,
required: [true, 'Must have a email address'],
trim: true,
unique: true,
},
firstName: {
type: String,
},
lastName: {
type: String,
},
services: {
type: [serviceSchema],
ref: 'Services',
default: [serviceSchema],
},
},
);
当我点击/api/v1/login 端点时,将使用服务文档正确创建一个新用户,但在 Mongoose 数据库中只存在一个用户集合。如何创建用户集合和服务集合?
编辑:以下是我在登录时创建/查找用户的功能。当找到现有用户时,如果找不到该用户,它将通过他们的电子邮件返回该用户,然后它将创建一个新用户...
这两种行为都符合预期包括将服务添加到新创建的用户。出乎意料的是,只有一个集合被添加到数据库中。
const login = catchAsync(async ({ body: { email, password } }, res, next) => {
if (!email || !password) {
return next(new AppError('Please provide email and password', 400));
}
const { Success } = await webApi(email, password);
const mongoUser = await User.findOne({ email });
if (Success && mongoUser) {
return createSendtoken(mongoUser, 200, res);
}
if (Success && !mongoUser) {
const newUser = await User.create({ email });
return createSendtoken(newUser, 201, res);
}
return next(new AppError('User not found', 404));
});
【问题讨论】:
标签: express mongoose mongoose-schema mongoose-populate