Javascript Can';t从关联模型检索数据
我有一个用户模型和一个配置文件模型Javascript Can';t从关联模型检索数据,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个用户模型和一个配置文件模型 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true }, password: { type:
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应该可以检索配置文件以及相关的用户名和电子邮件,但我无法得到任何回复。任何帮助都将不胜感激,谢谢
这是数据库中显示的配置文件文档:
{
"_id": {
"$oid": "5b0715288ae56b028b442e7b"
},
"handle": "johndoe",
"bio": "Hi, my name is John and I live in Toronto, ON, Canada!",
"location": "Toronto, ON",
"__v": 0
}
您正在向我们显示“用户”文档。那么您试图匹配的“配置文件”呢。出示那个文件。或者你只是认为猫鼬为你创造了“链接”?您的查询正在查看“Profile”`模型的
“user”
属性。它可能不存在,因此不会返回结果。或者您以前将其保存为“字符串”。上面的第一个代码段中显示了“用户”和“配置文件”文档。“配置文件”模型上有一个“用户”属性。我的理解是,通过将“user.type”指定为对象id,将“user.ref”指定为引用的集合,应该可以为我创建链接。这些链接是“schema:。您需要显示“数据库”中“集合”中显示的“文档”。您的理解不正确,因为引用不是“为您创建的”“您需要自己记录引用的信息。看起来你肯定误解了,但是显示实际的“文档内容”会让你清楚我已经复制并粘贴了mLab数据库中显示的配置文件文档。在原始帖子的底部。希望有帮助。