我正在尝试仅从用户文档中返回填充的配置文件。但是我似乎无法正确地编写逻辑代码...解决该问题的方法是什么?我只想选择个人资料字段以从用户返回。我想过也许可以尝试.select("profile).populate({ path: "profile"})
,但是那也不起作用。
User.findOne({ _id: req.user._id })
.populate({ path: "profile"}) <---
.then(user => {
res.json(user);
})
.catch(() => res.json({ Error: "User Account type is not valid" }));
用户架构
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
profile: {
type: Schema.Types.ObjectId,
refPath: "profile_type"
},
profile_type: {
type: String,
enum: ["PartnerAdminProfile", "DistrictAdminProfile", "MentorProfile"]
},
});
module.exports = User = mongoose.model("User", UserSchema);
配置文件架构
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const PartnerAdminProfileSchema = new Schema({ <----EDIT redefined schema name
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
profile_picture: {
type: Schema.Types.ObjectId,
ref: "Image",
date: {
type: Date,
default: Date.now
}
}
});
module.exports = PartnerAdminProfile = mongoose.model("PartnerAdminProfile", PartnerAdminProfilechema);
预期输出:
profile: {
user: "6546556654564",
profile_picture :{url:https://test.jpg}
}