在一个名为USERS的Mongoose模式中,我有一个名为Like的类型.每当一个用户喜欢另一个用户的帖子时,他的用户ID就会添加到点赞数组中.
router.put("/:id/like", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post.likes.includes(req.body.userId)) {
await post.updateOne({ $push: { likes: req.body.userId } });
res.status(200).json("The post has been liked");
} else {
await post.updateOne({ $pull: { likes: req.body.userId } });
res.status(200).json("The post has been disliked");
}
} catch (err) {
res.status(500).json(err);
}
});
因此,每当用户想要喜欢id为id的帖子(以及帖子创建者的用户ID)时,他就会转到以下路由-
Http://localhost:7001/api/post/:id/likes
然后以JSON格式发送他的用户ID.然后,应该将他的UserID附加到与PostSchema中的Like键相对应的数组中,我已经在下面将其与UserSchema一起包括在内.
const mongoose = require("mongoose");
const User = require("./user");
const PostSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
},
desc: {
type: String,
max: 500,
},
img: {
type: String,
},
likes: {
default: [],
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema);
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
following: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
desc: {
type: String,
max: 50,
},
city: {
type: String,
max: 50
},
relationship: {
type: Number,
enum: [1,2,3],
},
},
{ timestamps: true }
);
module.exports = mongoose.model( "User" , UserSchema);
现在,当我try 这样做时(Postman API屏幕截图和数据库截图如下所示),它不起作用,并且在响应时返回一个空array.