【发布时间】:2022-07-12 15:12:55
【问题描述】:
我对 mongodb 很陌生,实际上我正在尝试在后端实现 follow-unfollow 方法 数据库中有两种类型的用户
导师和学员
只有被指导者可以关注导师,导师只能接受请求
架构
导师
const MentorsSchema = mongoose.Schema({
name: { type: String, required: true },
designation: { type: String, required: true },
yearNdClass: {
type: String,
required: ["true", "year and class must be spciefied"],
},
respondIn: { type: String, required: true },
tags: {
type: [String],
validate: (v) => v == null || v.length > 0,
},
socialLinks: {
github: { type: String, default: "" },
twitter: { type: String, default: "" },
facebook: { type: String, default: "" },
instagram: { type: String, default: "" },
},
watNum: { type: Number, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
about: { type: String },
followers: [
{ type: mongoose.Schema.Types.ObjectId, ref: "Mentees", default: "" },
],
pending: [
{ type: mongoose.Schema.Types.ObjectId, ref: "Mentees", default: "" },
],
});
学员
const MenteeSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
yearNdClass: {
type: String,
required: ["true", "year and class must be spciefied"],
},
socialLinks: {
github: { type: String },
twitter: { type: String },
facebook: { type: String },
instagram: { type: String },
},
about: { type: String },
skillLooksFor: { type: String, required: true },
watNum: { type: Number, required: true },
following: [{ type: mongoose.Schema.Types.ObjectId, ref: "Mentors",default:"" },
],
});
您可以看到导师有两个字段,分别是跟随和待定数组,其中包括跟随导师的被指导者的 ID 和尚未被接受为跟随者的被指导者的 ID
我计划创建一个端点,当被指导者发出关注请求时,应该将其连接到指导者待处理数组中,以便他以后可以接受它
所以我的逻辑是这样的
// @desc follow a mentor
// @route POST /api/mentees/follow-mentor/:id
// @access private
menteeRoute.post(
"/follow-mentor/:id",
isAuthorisedMentee,
expressAsyncHandler(async (req, res) => {
const { id } = req.params;
const mentee = await Mentees.findById(req.mentee.id);
const mentor = await Mentors.findById(id).select("-password");
// console.log(mentor)
if (mentee) {
try {
await Mentees.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(id) },
{ $addToSet: { "following.0": mentor._id } },
{ new: true }
);
await Mentors.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(mentor._id) },
{
$addToSet: {
"pending.0": id,
},
},
{ new: true },
);
res.json({
data: {
mentor,
mentee,
},
});
} catch (error) {
console.log(error);
throw new Error(error);
}
}
})
);
但代码不起作用。 谁能帮我解决这个问题?
基本上,当学员发出关注请求时,它应该用id of mentor 更新mentee 的following 数组,它还应该用 mentor 更新 pending 数组id of the mentee
PS:也欢迎任何替代想法
【问题讨论】:
标签: node.js arrays mongodb express mongoose