代码之家  ›  专栏  ›  技术社区  ›  Marrone

InsertMany不在mongodb工作

  •  4
  • Marrone  · 技术社区  · 7 年前

    我对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 Post路线

    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 回复  |  直到 7 年前
        1
  •  1
  •   Ashh    7 年前

    不需要创建实例 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');
        })();
    });