javascript - 无法从关联模型中检索数据
问题描述
我有一个用户模型和一个配置文件模型。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = User = mongoose.model('users', UserSchema);
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
handle: {
type: String,
required: true
},
bio: {
type: String,
required: true
},
location: {
type: String,
required: true
}
});
module.exports = Profile = mongoose.model('profile', ProfileSchema);
我正在尝试在以下路线中检索用户名和电子邮件:
router.get('/', passport.authenticate('jwt', { session: false} ), (req, res) => {
console.log(req.user);
Profile.findOne({ user: req.user.id })
.populate('user', ['name', 'email'])
.then(profile => {
if (!profile) {
return res.status(404).json({error: 'Profile not found!'})
}
res.json(profile);
})
.catch(err => res.status(404).json(err));
});
即使用户存在于我的数据库中,我也会不断返回“找不到配置文件”。我也知道 id 正在传递,因为 console.log(req.user) 记录以下内容:
[0] Listening on port 8080!
[0] MongoDB connected
[0] { _id: 5afcab77c4b9a9030eee35a7,
[0] name: 'Harry',
[0] email: 'harry@gmail.com',
[0] password: '$2a$10$vOkK/Mpx04cR06Pon0t.2u5iKqGXetGuajKTZyBvLNWwgPjN6RO3q',
[0] __v: 0 }
将 req.user.id 传递给 Profile.findOne 应该检索配置文件以及相关的用户名和电子邮件,但我无法取回任何东西。任何帮助将不胜感激,谢谢!
这是出现在数据库中的 Profile 文档:
{
"_id": {
"$oid": "5b0715288ae56b028b442e7b"
},
"handle": "johndoe",
"bio": "Hi, my name is John and I live in Toronto, ON, Canada!",
"location": "Toronto, ON",
"__v": 0
}
解决方案
推荐阅读
- android - getExternalFilesDir(null).absolutePath 是否已修复?
- android - 如何仅为我的库模块/包获取包特定的崩溃报告/数据(通过 gradle 依赖项在某些应用程序中实现)
- react-native - 如何在本机反应中以 hh:mm:ss 格式获取两个日期之间的时间?
- excel - Excel 公式在两列中查找多个条件
- python - 无法将对象数据类型转换为日期时间格式
- javascript - WEBPACK - 如何从 javascript 导入中获取单个构建文件
- android - 当俯仰接近 90 度时,为什么滚动是不可预测的?
- node.js - 节点猫鼬不插入
- python - 从 nse 网站抓取即期汇率
- python - Python 最佳实践:如何给模块起别名