0

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.

2
  • use Promise.all so you can call then on all promises (after saving everything) Commented Feb 26, 2019 at 22:56
  • @molamk Will give it a try. Thanks will feedback if I get it working. Commented Feb 27, 2019 at 17:58

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Only problem is that the code doesn't throw an error, it simply just doesn't save anything.
Hum, ok... Can you copy your "obj" schema and what is inside your "data" object ? Also a call example of the function could help (to see if you pass the model by example). I use this kind of code and it save perfectly my docs. Maybe reccuring_length is 0 or frequency is not monthly.
You are correct, works a dream. I was passing recurring_length with a typo so nothing being saved. Thank you so much

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.