我在尝试使用 Mongoose 在 MongoDB Atlas 中执行 insertMany 操作时遇到问题。我收到的错误消息是:
MongoBulkWriteError: Expected 'insert' to be string, but got primitive.D instead.
我已经尝试通过在连接选项中将 retryWrites 设置为 false 来禁用可重试写入。然而,问题仍然存在。这是相关代码的简化版本
// Mongoose connection options
const mongooseOptions = {
retryWrites: false,
};
mongoose.connect(mongoURI, mongooseOptions);
看一下端点👇🏽
router.post('/insertMany', async (req, res) => {
try {
console.log(req.body);
const category = await Category.insertMany(req.body.list);
res.json(category);
} catch (error) {
console.log(error);
res.status(400).json({ error: error.message });
}
});
尝试过这个🧐
router.post('/insertMany', async (req, res) => {
try {
console.log(req.body);
let list = req.body.list.map(cat => Category(cat))
const category = await Category.insertMany(list);
res.json(category);
} catch (error) {
console.log(error);
res.status(400).json({ error: error.message });
}
});
请求通过 Postman 发送👇🏽
{
"list": [
{
"name": "Test Category",
"description": "Test category Desc"
}
]
}
错误日志🪵
Incoming POST request to /category/insertMany
{
list: [ { name: 'Test Category', description: 'Test category Desc' } ]
}
MongoBulkWriteError: Expected 'insert' to be string, but got primitive.D instead. Doc = [{insert [{collection category}]} {documents [[{name Test Category} {active true} {description Test category Desc} {_id ObjectID("65e19ac0e6f006f0730df049")} {__v 0}]]} {ordered true} {writeConcern [{w majority}]} {lsid [{id {4 [20 207 50 38 60 101 78 182 181 103 131 17 48 167 185 124]}}]} {$clusterTime [{clusterTime {1709283559 1}} {signature [{hash {0 [143 10 169 77 44 6 244 27 189 31 40 244 125 245 89 91 153 147 30 152]}} {keyId 7285440633500598274}]}]} {$db desejo}]
at resultHandler (/Users/jayedumindu/Dev/Desejo-Ecommerce/Backend/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js:294:29)
at /Users/jayedumindu/Dev/Desejo-Ecommerce/Backend/node_modules/mongoose/node_modules/mongodb/lib/utils.js:274:66
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
ok: 0,
code: 8000,
codeName: 'AtlasError',
writeErrors: [],
result: BulkWriteResult {
insertedCount: 0,
matchedCount: 0,
modifiedCount: 0,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: { '0': new ObjectId('65e19ac0e6f006f0730df049') }
},
insertedDocs: [
{
name: 'Test Category',
active: true,
description: 'Test category Desc',
_id: new ObjectId('65e19ac0e6f006f0730df049'),
__v: 0
}
],
[Symbol(errorLabels)]: Set(0) {}
}
型号👨🏽u200d💻
// models/Category.js
const mongoose = require('mongoose');
const categorySchema = new mongoose.Schema({
name: { type: String, unique: true },
active: { type: Boolean, default: true }, // Added for tracking the active status
description: String
});
module.exports = mongoose.model('Category', categorySchema, { collection: 'category' });
删除了可选参数
module.exports = mongoose.model('Category', categorySchema, { collection: 'category' });
到👇🏽
module.exports = mongoose.model('Category', categorySchema);
这有效!但是如何告诉 Atlas 使用用户给定的名称创建集合呢?