InsertMany在mongodb中不起作用

时间:2018-05-30 07:53:23

标签: mongodb mongoose

我对Mongoose和MongoDB本身很新,我试图保存一堆通过insertMany方法插入的文件,但它没有保存文档。

这是我的代码:

型号:

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邮政路线

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');
    })();
});

console.log向我显示了记录,但当我hostModel.save()时,我得到了hostModel.save is not a function

如何保存插入的文档?

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

无需在此处创建实例new hostModel() ...直接使用hostModel也不需要save()因为插入多个本身会创建集合...并确保{ {1}}包含对象数组

payload.data

答案 1 :(得分:0)

对于那些面临相同问题的人。我已将updateManycriteria结合使用,如下所示:

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')
                }
            });
    });
}