我对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
如何保存插入的文档?
非常感谢你的帮助!

最佳答案

不需要在这里创建实例new hostModel()。直接使用hostModel,也不需要save(),因为insert many本身会创建集合…并确保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');
    })();
});

10-06 14:19