FindOneAndUpdate 仅覆盖和更新第一个 id

FindOneAndUpdate overriding and updating only the first id

我只是想根据 id 更新内容,但无论我使用哪个 id,它都只会通过覆盖第一个 id 来更新它。 流程为路由=>控制器=>存储库 以下是代码: 路线 =>

router.post("/:pageId/content", async (req, res, next) => {
  try {
    const pageId = req.params;
    const pageContent = req.body;
    if (!pageId || !pageContent) {
      throw {
        statusCode: 200,
        customMessage: "All parameters are required"
      };
    }
    const result: any = await webpageController.createContent(
      pageId,
      pageContent
    );
    if (result.isError) {
      throw result.error;
    }
    res.status(200).json(result.data);
  } catch (error) {
    next(error);
  }
});

控制器=>

const createContent = async (pageId: any, pageContent: any) => {
  try {
    // calls repository to create content
    const result = await webpageRepository.createContent(pageId, pageContent);
    // if result is not success, throw error
    if (!result.success) {
      throw {
        statusCode: 400,
        customMessage: "Unable to create web page content"
      };
    }

    return {
      isError: false,
      data: result.data
    };

存储库 =>

export const createContent = async (pageId: any, content: any) => {
  try {
    const result = await webpage.findOneAndUpdate(pageId, { content });
    return {
      data: result,
      success: true
    };
  } catch (error) {
    logger.error(
      `at:"repositories/webpage/createContent" => ${JSON.stringify(error)}`
    );
    return {
      success: false
    };
  }
};

这里可以看出我在路由中使用的id和更新的id不一样。 我在这里做错了什么?

架构如下:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const webpage = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      maxlength: 25,
    },
    slug: {
      type: String,
    //   required: true,
    },
    url: {
      type: String,
      required: true,
      unique: true
    },
    content: Object,
  },
  {
    timestamps: true,
  },
);

export default mongoose.model('webpages', webpage);

我认为你应该使用字典作为参数。

const result = await webpage.findOneAndUpdate({_id:pageId.pageId}, {content});

您可以查看此文档了解如何使用“findOneAndUpdate”https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-started

这对我有用

const result = await webpage.findOneAndUpdate(   {_id:pageId.pageId} , { content });