1

this is my schema in mongoose

const companySchema = new mongoose.Schema({
    country: {
        type: String,
        required: true
    },
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    vaccine: [{
        name: String,
        price: Number,
        availibility: Number,
        needed: Number
    }]

}, {
    timestamps: true
});

I have created a form which gives the input for vaccine object(name price availability and needed) and its data is available in req.body. How do I append this using mongoose?

1
  • notify me if you needed to update the specific object in array besides of insertion Commented Mar 6, 2021 at 12:01

1 Answer 1

2

just use findOneAndUpdate() :

let vaccine ={ ... } // you object trying to add
let filter = { ... } // your filter you are trying to target the collection

Company.findOneAndUpdate(filter, { $addToSet:  {vaccine: vaccine}})

if you want get your updated result just use {new :true}.

full example:

let company = await Company.findOneAndUpdate(filter, { $addToSet:  {vaccine: vaccine}}, {new:true})
Sign up to request clarification or add additional context in comments.

Comments

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.