8

I'm fairly new to Mongoose and MongoDB itself and I'm trying to save a bunch of documents inserted via insertMany method but it is not saving the docs.

Here is my code:

Model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var hostSchema = new Schema({
    hostname: String,
    timestamp: Number,

});

var hostModel = mongoose.model('host', hostSchema, 'host');

module.exports = hostModel;

ExpressJS Post route

var mongoose = require('mongoose');
var hostModel = require('../../models/Host');

router.post('/host', function (req, res, next) {
    var payload = req.body;

    (async function(){
        var host = new hostModel();

        const insertMany = await hostModel.insertMany(payload.data);

        console.log(JSON.stringify(insertMany,'','\t'));

        const saveMany = await hostModel.save();

        res.status(200).send('Ok');
    })();
});

That console.log shows me the records but when I do hostModel.save() I get hostModel.save is not a function.

How can I save the inserted docs?

Thanks very much for the help!

Ashh
  • 44,693
  • 14
  • 105
  • 132
Marrone
  • 487
  • 2
  • 7
  • 18
  • please use that link you can find the detail https://stackoverflow.com/questions/37697448/mongodb-mongoose-insert-is-not-a-function/68662249#68662249 – Sonu P. Aug 05 '21 at 07:32

2 Answers2

5

No need to create instance new hostModel() here... use directly hostModel and also no need to save() as well because insert many itself creates the collections... and make sure payload.data has array of objects

router.post('/host', function (req, res, next) {
  const array = [{hostname: 'hostname', timestamp: 'timestamp'},
                 {hostname: 'hostname', timestamp: 'timestamp'}]

    var payload = req.body;

    (async function(){

        const insertMany = await hostModel.insertMany(array);

        console.log(JSON.stringify(insertMany,'','\t'));

        res.status(200).send('Ok');
    })();
});
Ashh
  • 44,693
  • 14
  • 105
  • 132
  • 1
    I tried that but I still don't get the docs saved to the collection. According to Mongoose docs insertMany does not trigger save middleware. Thanks anyway :-) – Marrone May 30 '18 at 08:04
  • this is my data array "data": [ { "hostname": "localhost", "timestamp": 1527668059689 } ] Obviously it contains more than one item... just posted this as an example. – Marrone May 30 '18 at 08:16
  • Still the same result with the hard coded items... none saved. – Marrone May 30 '18 at 08:20
  • 1
    This is the result for console.log(insertMany): [ { "_id": "5b0e5e95b5f6844c5a8d5f02", "hostname": "localhost", "timestamp": 1527668059689, "__v": 0 }, { "_id": "5b0e5e95b5f6844c5a8d5f03", "hostname": "localhost", "timestamp": 1527668059789, "__v": 0 } ]. It gets the ids returned... kinda weird to not be saved. – Marrone May 30 '18 at 08:25
  • Hi @Marrone, I'm facing a similar issue. Were you able to fix this? – Lizzy Mar 11 '20 at 06:06
  • Hi @Lizzy, please, check my answer. I've moved to the updateMany using the "criteria" – Marrone Mar 11 '20 at 15:22
0

For those facing the same issue. I've solved it using the updateMany with criteria as follows:

router.post('/heatmap', function (req, res, next) {
    let payload = req.body;

   (async function(){

        let heatmapDate = new Date(payload[0].heatmapdata[0].timestamp).toISOString().substring(0, 10);

        payload[0].heatmapDate = heatmapDate;

        let sessionData = payload[0];

        sessionData.sessionrecordheatmap = payload[0].heatmapdata;

        let criteriaSession = {
            sessionId:{ $eq: payload[0].sessionId}
        };

        const updatetManySession = await updateManySessionRecord(sessionrecordModel, criteriaSession, sessionData);

        res.status(200).send(updatetManyHeatmap);
    })();
});

async function updateManySessionRecord(schema, criteria, data){
    return new Promise((resolve, reject) => {
        schema.updateMany(criteria, 
            {
                id: data.id,
                clientIp: data.clientIp,
                device: data.device,
                heatmapDate: data.heatmapDate,
                protocol: data.protocol,
                hostname: data.hostname,
                pagePath: data.pagePath,
                pageImage: data.pageImage,
                pageTitle: data.pageTitle,
                clientHeight: data.clientHeight,
                clientWidth: data.clientWidth,
                $push: {
                    sessionrecordheatmap: data.sessionrecordheatmap,
                }
            },
            { 
                multi: true,
                upsert: true
            }, 
            function(err, res) {
                if (err) { 
                    console.log('ERROR - UPDATE MANY SESSIONRECORD: ' + err);
                    reject('insertFirst');
                } 
                else{ 
                    resolve('ok')
                }
            });
    });
}
Marrone
  • 487
  • 2
  • 7
  • 18