InsertMany在mongodb中不起作用 [英] InsertMany not working in mongodb

查看:536
本文介绍了InsertMany在mongodb中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Mongoose和MongoDB本身还很陌生,我正尝试保存通过insertMany方法插入的一堆文档,但它没有保存文档.

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.

这是我的代码:

型号:

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.

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

如何保存插入的文档?

非常感谢您的帮助!

推荐答案

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

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

这篇关于InsertMany在mongodb中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆