我对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中不起作用
发布评论