Mongoose如何批量插入多个对象?调用save方法仅存入单个数组对象怎么办
Mongoose批量插入文档异常问题修复方案
问题根因
new Course() 是单个文档的构造方法,仅支持传入单个文档的属性对象生成实例。你传入对象数组时,Mongoose无法识别为多个待创建文档,只会错误将数组内容映射到单个文档的字段上,最终仅生成1条字段不符合预期的文档。
修复方法
使用Mongoose提供的Model.insertMany()静态方法实现批量插入,该方法原生支持传入文档数组一次性创建多条独立文档,执行效率更高。
修改后代码
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/playground') .then(() => console.log('Connected with MongoDB...')) .catch(err => console.log("Couldn't connect with MongoDB!!!", err)); const courseSchema = new mongoose.Schema({ name: String, author: String, edition: Number, tags: [ String ], data: {type: Date, default: Date.now}, isPublished: Boolean }) const Course = mongoose.model('Course', courseSchema); async function createCourse() { // 直接调用insertMany传入文档数组即可 const result = await Course.insertMany([{ name: "Node Course", author: "Ammar Siddiqi", edition: 3, tags: ['node', 'backend', 'server'], isPublished: true },{ name: "React Course", author: "Mosh", edition: 3, tags: ['Functionalties', 'frontend', 'server'], isPublished: true }]); console.log(result); } createCourse();
补充说明
如果需要对每个文档做单独的预处理逻辑,也可以循环遍历每个数据对象,逐个new Course()生成实例后调用save()方法,不过批量插入场景优先使用insertMany(),性能更优。
内容的提问来源于stack exchange,提问作者Ammar Siddiqi
相关产品推荐
相关产品推荐

