tapos ghosh
tapos ghosh

Reputation: 2202

Mongoose ORM async await

anyone help me how can i manage this code using async and await feature. My requirement is after inserting 100 data then mongo database disconnected.

var faker = require('faker');
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/shopping');
    mongoose.Promise = global.Promise;
    var Product = require('../models/product');



    async function insertDocument(){
        for(var i=0;i<=100;i++){
            try{
                var product = new Product({
                    imagePath:faker.image.image(),
                    title:faker.commerce.productName(),
                    description:faker.lorem.paragraph(),
                    price:faker.commerce.price()
                });

                product.save();
            }catch (err) {
                console.log(err);

            }
        }


    }
     insertDocument().then(function () {
      //  mongoose.disconnect();

    });

Upvotes: 1

Views: 360

Answers (1)

Pace
Pace

Reputation: 43817

product.save() returns a promise. If you want to insert the 100 documents serially (one after the other) use await. If you want to insert the 100 documents in parallel you don't need async and should use Promise.all

Sequential

async function insertDocument(){
    for(var i=0;i<=100;i++){
        try{
            var product = new Product({
                imagePath:faker.image.image(),
                title:faker.commerce.productName(),
                description:faker.lorem.paragraph(),
                price:faker.commerce.price()
            });

            await product.save();
        }catch (err) {
            console.log(err);

        }
    }

}

Parallel

function insertDocument(){
    let promises = [];
    for(var i=0;i<=100;i++){
        var product = new Product({
            imagePath:faker.image.image(),
            title:faker.commerce.productName(),
            description:faker.lorem.paragraph(),
            price:faker.commerce.price()
        });

        promises.push(product.save());
    }

    return Promise.all(promises);
}

Upvotes: 3

Related Questions