我有2个型号:
以下是用户模型:
const userSchema = new mongoose.Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
passwordResetToken: String,
passwordResetExpires: Date,
facebook: String,
twitter: String,
tokens: Array,
profile: {
name: String,
gender: String,
location: String,
website: String,
picture: String
}
}, { timestamps: true });
这是Revive模型:
const reviveSchema = new mongoose.Schema({
reviveShowName: {type: String, required: true},
reviveTitle: {type: String, required: true},
reviveCategory: {type: String, required: true},
reviveGoal: {type: Number, required: true},
revivePhoto: {type: String, required: true},
reviveVideo: {type: String},
reviveStory: {type: String},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
name: String
}
}, { timestamps: true });
在Revive模型中,我尝试引用作者并获取作者的ID并且有效...我如何从个人资料中获取名称 - >名称...?显然name: String
是错误的......
答案 0 :(得分:3)
Mongoose关系基于嵌套对象的ref
和type
值工作。在您的情况下,您已将id
的{{1}}属性与author
模型相关联。
如果您想使用用户信息填充User
,您应该这样做:
author
然后在您的查询中,您只需使用填充
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}