Home > OS >  Modified model in node.js not reflecting on MongoDB
Modified model in node.js not reflecting on MongoDB

Time:01-08

I just modified my model Order for my API because I need a value to pass a condition. But unfortunately, my new set of properties (orderStatus) on my collection did not reflect on my MongoDB database.

I don't need to input a value for the property (orderStatus) since I set a default value ("Pending"). I tried to delete the entire collection orders to see any changes but there were none. Is there something else I need to do on my MongoDB or any command on the git?

Here is my code for my model

const mongoose = require("mongoose");

const orderSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: [true, "User ID is required!"]
    },
    products: [
        {   
            productId: {
                type: String,
                required: [true, "Product ID is required!"]
            },
            quantity: {
                type: Number,
                required: [true, "Quantity is required!"],
                min: 1,
                default: 1
            },
            subtotal: {
                type: Number,
                required: [true, "Subtotal is required"],
                default: 0 
            }
        }
    ],
    totalAmount: {
        type: Number,
        required: [true, "Total Amount is required!"],
        default: 0
    },
    orderStatus: {
        type: String,
        required: [true, "Order Status is required!"],
        default:"Pending"
    },
    purchasedOn: {
        type: Date,
        default: new Date
    }

});

module.exports = mongoose.model("Order", orderSchema);

and a screenshot of my database

and a screenshot of my database

I will really appreciate your help! Thank you so much!

CodePudding user response:

Your documents which were already created will not reflect your new schema field. Since those fields only will get reflected on the update only. So, add orderStatus as pending as the default. You must migrate those documents by the update method. This is going to be a one-time process.

So, in the terminal, you can write the following code and run

db.collection.update({}, {$set: {orderStatus: "Pending"}}, {upsert: true, muti: true})

Or you are comfortable with the code itself you can write your update code in your project itself like this

await orderModel.updateMany({}, {$set: {orderStatus: "Pending"}}, {upsert: true})

and make an API and call this code.

In this process, you will see that in your documents that new key called orderStatus with pending value has been created.

  • Related