在我的
node.js
项目中,我有一个简单的架构,其中包含名为 likes
的字段,我在其中添加喜欢帖子的用户:
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
likes: [{
type: mongoose.Schema.Types.ObjectId, ref: 'User'
}]
});
module.exports = mongoose.model('post', postSchema);
当我收到请求时,API 必须将
userId
添加到帖子中,然后保存。在此之前,我想检查 userId
是否在列表中。所以,我写了
const postId = req.params.id;
const userId = req.body.userId;
const postToUpdate = await Posts.findById(postId).populate('likes');
if (!postToUpdate.likes.includes(userId)) {
// code
}
但是
includes
不是一个有效的函数。如何检查 userId
是否尚未在喜欢列表中?
includes 在您的情况下不起作用,因为 likes 数组存储 Mongoose ObjectIds 并包含检查对象引用而不是值。要比较ObjectId,需要使用Mongoose提供的equals方法。
请修改您的代码
const postId = req.params.id;
const userId = req.body.userId;
const postToUpdate = await Posts.findById(postId).populate('likes');
if (!postToUpdate.likes.some(like => like.equals(userId))) {
// Add userId to the likes array and save the post
postToUpdate.likes.push(userId);
await postToUpdate.save();
}
some 将迭代 likes 数组并使用 equals 来正确比较 userId。这样,您就可以避免重复点赞。