Home > Back-end >  FindOneAndUpdate overriding and updating only the first id
FindOneAndUpdate overriding and updating only the first id

Time:02-11

I am simply trying to update the content according to the id, but whichever id I am using, it updates only the first id by overriding it. The flow goes as routes => controller => repository Following is the code: Routes =>

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);
  }
});

Controller =>

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
    };

Repository =>

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
    };
  }
};

Here it can be seen that the id I have used in the route and the id getting updated is different. What am I doing wrong here? enter image description here

Following is the schema:

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);

CodePudding user response:

I think you should use a dictionary as the parameter.

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

You can check on this documentation about how to use the "findOneAndUpdate" https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-started

CodePudding user response:

This worked for me

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