InsertMany在mongodb中不起作用

编程入门 行业动态 更新时间:2024-10-24 20:13:47
本文介绍了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中不起作用

本文发布于:2023-11-22 13:05:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   InsertMany   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!