【问题标题】:InsertMany not working in mongodbInsertMany 在 mongodb 中不起作用
【发布时间】:2020-03-11 23:23:33
【问题描述】:

我对 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

如何保存插入的文档?

非常感谢您的帮助!

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

不需要在这里创建实例new hostModel()...直接使用hostModel,也不需要save(),因为插入很多本身会创建集合...并确保payload.data具有对象数组

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

【讨论】:

  • 我试过了,但我仍然没有将文档保存到集合中。根据 Mongoose 文档 insertMany 不会触发保存中间件。无论如何谢谢:-)
  • 这是我的数据数组 "data": [ { "hostname": "localhost", "timestamp": 1527668059689 } ] 显然它包含多个项目...只是作为示例发布.
  • 硬编码项目的结果仍然相同...没有保存。
  • 这是 console.log(insertMany) 的结果: [ { "_id": "5b0e5e95b5f6844c5a8d5f02", "hostname": "localhost", "timestamp": 1527668059689, "__v": 0 } ,{“_id”:“5b0e5e95b5f6844c5a8d5f03”,“主机名”:“localhost”,“时间戳”:1527668059789,“__v”:0}]。它得到了返回的ID......有点奇怪不被保存。
  • 嗨@Marrone,我面临着类似的问题。你能解决这个问题吗?
【解决方案2】:

对于那些面临同样问题的人。我已经使用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')
                }
            });
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2016-02-26
    • 2021-06-18
    • 2018-09-05
    相关资源
    最近更新 更多