在一个名为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.

databasescreenshot

PostmanAPIScreenShot

推荐答案

您应该进行以下更改:

1-)更新POST架构中的UserID和Like字段,使其具有正确的类型和引用.

const PostSchema = new mongoose.Schema(
    {
        userId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User',
        },
        //other fields
        likes: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'User',
            },
        ],
    },

    { timestamps: true }
);

2-)更新类似的路径,如果发送错误的帖子id,则处理未找到帖子的情况.

router.put('/:id/like', async (req, res) => {
    const postId = req.params.id;
    const { userId } = req.body;

    try {
        const post = await Post.findById(postId);

        if (post == null) {
            return res.status(404).send('Post with id not found');
        }

        if (!post.likes.includes(userId)) {
            await post.updateOne({ $push: { likes: userId } });
            res.status(200).json('The post has been liked');
        } else {
            await post.updateOne({ $pull: { likes: userId } });
            res.status(200).json('The post has been disliked');
        }
    } catch (err) {
        res.status(500).json(err);
    }
});

注意:您也应该应用相同的更改,追随者和以下领域,就像我在点赞领域.

Javascript相关问答推荐

复合密钥查找在mongoDB中未按预期工作

Math.random超出了最大调用堆栈

同步功能在中间停止

为什么我无法使用useMemo()停止脚本渲染?

React状态变量在使用++前置更新时引发错误

如何提取Cypress中文本

如何使用Echart 5.5.0创建箱形图

Vega中的模运算符

有条件的悲剧

django无法解析余数:[0] from carray[0]'

基于变量切换隐藏文本

将自定义排序应用于角形数字数组

Promise Chain中的第二个useState不更新

Chromium会将URL与JS一起传递到V8吗?

本地库中的chartjs-4.4.2和chartjs-plugin-注解

Reaction组件在本应被设置隐藏时仍显示

TinyMCE 6导致Data:Image对象通过提供的脚本过度上载

在VS代码上一次设置多个变量格式

使用插件构建包含chart.js提供程序的Angular 库?

本地损坏的Java脚本