Mongoose (mongodb) batch insert?

后端 未结 8 1991
灰色年华
灰色年华 2020-11-27 10:15

Does Mongoose v3.6+ support batch inserts now? I\'ve searched for a few minutes but anything matching this query is a couple of years old and the answer was

8条回答
  •  清歌不尽
    2020-11-27 10:45

    Here are both way of saving data with insertMany and save

    1) Mongoose save array of documents with insertMany in bulk

    /* write mongoose schema model and export this */
    var Potato = mongoose.model('Potato', PotatoSchema);
    
    /* write this api in routes directory  */
    router.post('/addDocuments', function (req, res) {
        const data = [/* array of object which data need to save in db */];
    
        Potato.insertMany(data)  
        .then((result) => {
                console.log("result ", result);
                res.status(200).json({'success': 'new documents added!', 'data': result});
        })
        .catch(err => {
                console.error("error ", err);
                res.status(400).json({err});
        });
    })
    

    2) Mongoose save array of documents with .save()

    These documents will save parallel.

    /* write mongoose schema model and export this */
    var Potato = mongoose.model('Potato', PotatoSchema);
    
    /* write this api in routes directory  */
    router.post('/addDocuments', function (req, res) {
        const saveData = []
        const data = [/* array of object which data need to save in db */];
        data.map((i) => {
            console.log(i)
            var potato = new Potato(data[i])
            potato.save()
            .then((result) => {
                console.log(result)
                saveData.push(result)
                if (saveData.length === data.length) {
                    res.status(200).json({'success': 'new documents added!', 'data': saveData});
                }
            })
            .catch((err) => {
                console.error(err)
                res.status(500).json({err});
            })
        })
    })
    

提交回复
热议问题