node.js - 查找刚刚在路由中创建的用户的_id
问题描述
我正在制作 MERN 应用程序的快速原型,我有一个后端问题:我有一个用户模型和一个类别模型,当用户注册时,我需要用从用户对象导出的一些基本信息填充类别模型以后可以编辑。我想为每个类别分配一个引用到刚刚创建的帐户 ID。问题是我不明白如何检索刚刚创建的用户 ID。这是我的路线(是的,没有重构,抱歉):
// @route POST api/users/register
// @desc Register user
// @access Public
router.post('/register', (req, res)=>{
//Validate req.body
const {errors, isValid} = validateRegisterInput(req.body);
//Check validation
if(!isValid){
return res.status(400).json(errors);
}
User.findOne({ email: req.body.email })
.then(user => {
if(user){
errors.email = 'Email already exists';
return res.status(400).json(errors)
} else {
const avatar = gravatar.url(req.body.email, {
s: '200', //Size
r: 'pg', //Rating
d: 'mm' //Default
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
//Hash the password and save
bcrypt.genSalt(10, (err, salt)=>{
bcrypt.hash(newUser.password, salt, (err, hash)=>{
if(err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err))
})
});
//Fill user categories with default categories
defaultIcons.map((icon) => {
const newCategory = new Category ({
name: icon.name,
type: icon.type,
icon: icon.icon
})
newCategory.save();
});
}
})
});
这是类别架构:
//Create Schema
const CategorySchema = new Schema({
//Every account is associated with actual User schema by id
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String,
required: true
},
type: {
type: String,
required: true
},
icon: {
type: String,
required: true
}
})
什么是最好的解决方案?像我正在做的那样为类别设置一个单独的模式会更好,还是我可以在用户模式中实现一个对象字段数组?
解决方案
你做的部分
if(err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err))
你有你已user
解决的承诺。你可以
const newCreatedUserID = user._id
获取刚刚创建的用户 ID。
推荐阅读
- c# - StateMachineException 越过了 AppDomain 边界
- apache-kafka - 就处理时间而言,Kafka 在应用程序中是多么受欢迎,而没有 JMS 选择器中的过滤器。
- ios - MKMapView 的状态恢复略微缩小
- android - MPAndroidChart 条形值在放大时隐藏
- string - 将不同模式的字符串转换为日期
- bash - 'sed' 替换最后一个模式并删除其他模式
- javascript - 错误:检测到无法访问的代码 ionic 3 天气应用程序
- r - 在 ggplot 中为子组使用不同的颜色(和透明度)
- python - ValueError:找到包含 0 个样本的数组(形状=(0, 40)),而至少需要 1 个
- jquery - jquery mobile如何仅禁用单选按钮组的一种选择