这些是我从配置文件 API 的 get 请求中获得的对用户
的响应
"user": "5cc3a4e8d37a7259b45c97fe"
我正在寻找的是
"user":{
"_id": "5cc3a4e8d37a7259b45c97fe",
"name":"Jhon Doe",
}
这是我的代码:
Profile.findOne({
user: req.user.id
})
.populate('user',['name']) // I added this line to populate user object with name
.then(profile=>{
if(!profile){
errors.noprofile = 'There is no profile for this user'
return res.status(404).json(errors);
}
res.json(profile)
})
.catch(err => res.status(404).json(err));
但是,我收到这些错误:
{
"message": "Schema hasn't been registered for model \"users\".\nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"
}
我错过了什么
配置文件架构
const ProfileSchema = new Schema({
user:{
type: Schema.Types.ObjectId,
ref: 'users'
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
website: {
type: String,
}
})
这是我的用户架构的样子
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
name:{
type: String,
required: true,
},
email:{
type: String,
required: true,
},
password:{
type: String,
required: true,
},
avator:{
type: String,
},
date:{
type: Date,
default: Date.now,
}
});
module.exports = User = mongoose.model('Users', UserSchema)
最佳答案
您在Profile
架构中引用的架构是users
,但您已将用户架构保存为Users
。所以我想说你需要更新你的 Profile
架构:
const ProfileSchema = new Schema({
user:{
type: Schema.Types.ObjectId,
ref: 'Users'
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
website: {
type: String,
}
})
可以在此行中找到保存您的用户
架构的名称
module.exports = User = mongoose.model('Users', UserSchema)
关于javascript - 如何使用字段填充用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55894244/