【发布时间】:2025-07-20 12:55:01
【问题描述】:
我试图弄清楚如何通过每次访问页面时递增 +1 来更新字段,如果从未访问过,则将其添加到数据库中。
目前,这就是我所拥有的,但似乎并没有多大作用。我一定是在某个地方出错了,我还没有实现如果页面从未被查看过的部分,那么在存储在数据库中的数组中创建一个新对象。
小提示:如果我查看与存储在数据库中的 ID 相同但没有发生增量的页面,它们确实匹配相同 ID 的地图。
exports.pageVisitCount = (req, res, next) => {
User.findById({
_id: req.userData.userId
}, 'visits', function (err, pageVists) {
if (err) {
res.status(401).json({
message: "Error Occured!"
})
} else {
const pageCounts = pageVists.visits;
pageCounts.map(page => {
const postViewed = req.body.postId;
if (page.postId.toString() === postViewed) {
User.findByIdAndUpdate({
_id: req.userData.userId
}, {
$set: {
visits: [{
"postId": postViewed,
$inc: { visitCount: 1 }
}]
}
}, {
upsert: false
},
(err) => {
if (err) {
res.status(401).json({
message: "Error Occured!"
})
} else {
res.status(200).json({
message: "Update successful!"
})
}
});
}
});
}
});
}
这是我正在使用的架构:
const visitsSchema = new Schema ({
postId: {
type: String
},
visitCount: {
type: Number
}
})
const userSchema = mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
role: {
type: String,
required: true
},
answers: {
type: String
},
visits: [visitsSchema]
});
非常感谢任何反馈,我想提一下我是后端新手,谢谢!
【问题讨论】:
标签: javascript node.js mongoose mongoose-schema