October 27, 2024
Chicago 12, Melborne City, USA
javascript

Issue in updating the nested array object in MongoDB using mongoose


Here is my code for my API endpoint api/admin/changeStock in Next.js app

import connectToDb from "@/lib/mongodb";
import { Coco, Brand } from "@/models/model";
import { NextResponse } from "next/server";

export async function POST (req) {
    const { brand, modelname, stockNum } = await req.json();
    await connectToDb();
    const selectedBrandModel = await Coco.findOne({ brand });
    const model = selectedBrandModel.models.find(model => model.modelname === modelname); // version A
    console.log("model from /changeStock: " + model) // shows version A

    if (!model?.productIDs) {
        console.log("In if from /changeStock");
        model.productIDs = ["d1", "d2"]; // version B
        console.log("model from /changeStock after inserting: " + model); // shows version A
        console.log("model.productIDs from /changeStock after inserting: " + model.productIDs); // shows the correct model.productIDs from version B
        selectedBrandModel.markModified("models");
        await selectedBrandModel.save(); // does not save the updated version still remain version A in database
        return NextResponse.json({ message: "changed1"}, { status: 200 });
    } else {
        console.log("in else /changeStock");
        model.productIDs = ["s1", "s2", "s3", "s4"];
        selectedBrandModel.markModified("models");
        await selectedBrandModel.save();
        return NextResponse.json({ message: "changed2"}, { status: 200 });
    }
}

I do not get it that why the console logs are not giving me the updated model which is an object in the selectedBrandModel.models array also await selectedBrandModel.save() does not save the updated version B of models in database. Right now no object (model) inside the models array in brand have a property model.productIDs so if(!model?.productIDs) is always true.

Also for some reason when i just try to change the modelname like model.modelname = modelname + " |Modified"; instead of adding a property like i was above model.productIDs = ["d1", "d2"]; then that works totally fine.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video