[英]Creating a relationship between models with additional info in Mongo, Express, Node
對 Node 來說有點新,並且一直在努力處理這種 model 關系,但在這里找不到答案。
我有四個模型我試圖在它們之間建立關系:
當用戶對某個主題的課程發表評論時,我想跟蹤用戶 model 的“主題分數”。
因此,如果用戶查看了編程課程,他們的編程主題分數應該會得到 +10。 然后我應該能夠查詢 User.scores.programming 以獲得他們的編程分數。
評論創建得很好,這只是我遇到問題的主題評分部分。
這是我的用戶模式的設置方式,只是相關部分:
const userSchema = new mongoose.Schema({
...
scores: [{
topic: {
type: mongoose.Schema.ObjectId,
ref: 'Topic'
},
score: {
type: Number,
default: 0
}
}]
});
這是我目前嘗試增加分數的代碼:
const updateUserScores = async (userId, course) => {
const user = await User.findOne({_id: userId}).populate('scores');
const userScores = user.scores;
let topics = await Course.findOne({_id: course}).populate('tags');
topics = topics.tags.map(x => x._id);
// I know it works for here to get the array of topics that they need to be scored on
// Then we need to go through each topic ID, see if they have a score for it...
// If they do, add 10 to that score. If not, add it and set it to 10
for (topic in topics) {
const operator = userScores.includes(topic) ? true : false;
if (!operator) {
// Add it to the set, this is not currently working right
const userScoring = await User
.findByIdAndUpdate(userId,
{ $addToSet: { scores: [topic, 10] }},
{ new: true}
)
} else {
// Get the score value, add 10 to it
}
}
}
我知道我在這里可能有一些不同的問題,而且我一直非常堅持取得進展。 我可以查看的任何指針或示例都會非常有幫助!
好吧,經過一番折騰,我終於弄明白了。
用戶 model 保持不變:
scores: [{
topic: {
type: mongoose.Schema.ObjectId,
ref: 'Tag'
},
score: {
type: Number,
default: 0
}
}]
然后讓代碼在他們留下評論時增加他們在每個主題上的分數:
const updateUserScores = async (userId, course) => {
const user = await User.findOne({_id: userId}).populate({
path : 'scores',
populate: [
{ path: 'topic' }
]
});
let userScores = user.scores;
userScores = userScores.map(x => x.topic._id);
let topics = await Course.findOne({_id: course}).populate('tags');
topics = topics.tags.map(x => x._id);
for (t of topics) {
const operator = userScores.includes(t) ? true : false;
if (!operator) {
const userScoring = await User
.findByIdAndUpdate(userId,
{ $addToSet: { scores: {topic: t, score: 10}}},
{ new: true}
);
} else {
const currentScore = await user.scores.find(o => o.topic._id == `${t}`);
const userScoring = await User
.findByIdAndUpdate(userId,
{ $pull: { scores: {_id: currentScore._id}}},
{ new: true }
)
const userReScoring = await User
.findByIdAndUpdate(userId,
{ $addToSet: { scores: {topic: t, score: (currentScore.score + 10)}}},
{ new: true }
)
}
}
}
丑陋而不是超級優雅,但它完成了工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.