Dom Needham
Dom Needham

Reputation: 69

Saving with mongoose to mongodb in a loop

I want to save an object multiple times, with a change to the date field - adding one month per iteration.

A for loop doesn't work due to node async nature.

const saveMany = (req, res, obj, data) => {
    let saves = [];
    if (data.frequency === 'monthly') {
         let i = 0;
         for (let i = 0; i < data.reccuring_length; i++) {
            const newEntry = new obj(data);
            if (i != 0) newEntry.created_date.addMonths(1) //using datejs
            newEntry.save((err, entry) => {
                if (err) {
                    return res.status(400).send({
                        message: err
                    });
                }
                saves.push(entry);
            })

        }) //end of for loop
        return res.json(saves)

    } //end of if
}

I've seen stuff about promises / the async library but can't make a working implementation (I am new to this though so could be missing something obvious).

Any help is appreciated :)

EDIT: Saving To MongoDB In A Loop

Found this link which is relevant, but if anyone has other suggestions that would be great.

EDIT 2:

Just realised my code has camelcase and snake case, changing in my code to make all object data snake case.

Upvotes: 0

Views: 809

Answers (1)

Veldars
Veldars

Reputation: 121

I think you can do somethings like that:

const saveMany = async (req, res, obj, data) => {
let saves = [];
if (data.frequency === 'monthly') {
     let i = 0;
     for (let i = 0; i < data.reccuring_length; i++) {
        const newEntry = new obj(data);
        if (i != 0) newEntry.created_date.addMonths(1) //using datejs
        try{
          const entry= await newEntry.save();
          saves.push(entry);
        } catch(err) {
          return res.status(400).send({ message: err });
        }
    }) //end of for loop
    return res.json(saves)

} //end of if
}

Upvotes: 1

Related Questions