Home > Back-end >  Is there a way to get data from db before update for MongoDb - Mongoose
Is there a way to get data from db before update for MongoDb - Mongoose

Time:05-11

I want to do an update method for my project but i couldn't solve this issue. My model has a field call slug. If I need I add data to make this value unique. However, i am using findByIdAndUpdate method on my update function. I am wondering about that is there a way to get data before update this model? Do I have to make at least 2 different requests to my db to get the old data or does this method I use give me a chance to compare data? Because if the title field has changed I need to compare it and generate the new slug value.

Category model

const mongoose = require('mongoose')

const CategorySchema = mongoose.Schema({
    title: {
        type: String,
        required: true,
        trim: true,
        minLength: 3,
        maxLength: 70
    },
    description: {
        type: String,
        requried: true,
        trim: true,
        minLength: 30
    },
    coverImage: {
        type: String,
        trim: true
    },
    slug: {
        type: String,
        unique: true,
        required: true
    }
}, {collection: "categories", timestamps: true})

module.exports = mongoose.model('category', CategorySchema);

Update function

const update = async (req, res, next) => {
    delete req.body.createdAt;
    delete req.body.updatedAt;

    try {
        const data = req.body;
        data.coverImage = req.file ? req.file.path.replace(/\\/g, "/") : undefined;
        data.slug = data.title ? slugCreator(data.title, null): undefined;
        const result = await CategoryModel.findByIdAndUpdate(req.params.categoryId, data, { new: true, runValidators: true });
        if (result) {
            return res.json({
                message: "Category has been updated",
                data: result
            });
        }else{
            throw createError(404, "Category not found.")
        }
    } catch (error) {
        next(createError(error));
    }
};

CodePudding user response:

You could solve your problems first by getting the documents and then do the update with the save method like the following example

const update = async (req, res, next) => {
  delete req.body.createdAt;
  delete req.body.updatedAt;
  try {
    const data = req.body;
    //here you have the current category
    const category = await CategoryModel.findById(req.params.categoryId);
    if (!category) {
      throw createError(404, 'Category not found.');
    }
    //do all you comparation and setting the data to the model...
    category.slug = data.title ? slugCreator(data.title, null) : undefined;
    category.coverImage = req.file
      ? req.file.path.replace(/\\/g, '/')
      : undefined;

    await category.save();

    return res.json({
      message: 'Category has been updated',
      data: category,
    });
  } catch (error) {
    next(createError(error));
  }
};
  • Related