0

I have the following code in my page. Whenver I click on the "Add new field button" a new fields gets added to the page. What I need to accomplish is to insert every single new field into my mongodb database array.

    function addInput(divName){
        if (counter == limit)  {
            alert("You have reached the limit of adding " + counter + " inputs");
        }
        else {
            var newdiv = document.createElement('div');
            newdiv.className = "row-inputs";
            newdiv.innerHTML = '<input type="text" name="productName" placeholder="product name" class="q-product-name">'  + 
            '<input type="number" name="quantity" placeholder="1" class="q-quantity" value=1>' +
            '<input type="text" name="pricePerUnit" placeholder="price" class="q-price">' +
            '<input type="text" name="itemTotal" placeholder="price" class="q-total">';
            document.getElementById(divName).appendChild(newdiv);
            counter++;
        }
    }

The above is my schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

var InventorySchema = Schema({
    created_at: {type: Date, default: Date.now },
    name: String,
    list: [{
        product_name: String,
        quantity: Number,
        pricePerUnit: Number,
        itemTotal: Number
    }],
    invoiceTotal: Number,
    comment: String,
    dueDate: Date
})

var inventory = mongoose.model('inventory', InventorySchema);

module.exports = inventory;

How can I tell mongoose to add every fields created dynamically to my database?

Thank you so much!

1 Answer 1

1

You can not insert new fields if you have defined a static schema with types defined.

However, You can specify type of an attribute ({}) it will allow anything to be saved to it. If you want one of your object or whole schema dynamic then you can define a schema like this:

var InventorySchema = Schema({
    created_at: {type: Date, default: Date.now },
    name: String,
    list: [{ }],
    invoiceTotal: Number,
    comment: String,
    dueDate: Date
})

Caution: You will not be able to validate or typecast any of your dynamic variables.

Sign up to request clarification or add additional context in comments.

2 Comments

In that case, how would I loop true each different product? So far, I only get one "product name" with different values, instead a several product name with its own value.
unable to understand your concern. can you post the code snippet?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.