首页 > 解决方案 > E11000 重复键错误收集:db.products 索引:product_id_1 重复键:{ product_id:null }

问题描述

请任何人帮助我。已经两天了,我因获取所有产品而被阻止我在执行 GET 操作时遇到重复键错误我试图删除({})或 deleteMany({})或两者或只是我的 ctrllr 中的一个数据库,但它仍然在同样的错误...我不明白发生了什么

这是我的product.ctrl

const productCtrl = {
  sendDatasProductToMoongoose: async (req, res) => {
    try {
      await Product.deleteMany({})
                    .remove({});  
      const createdProducts = await Product.insertMany(data.products);
      console.log('Data Import Sucess createdProducts',createdProducts);
      res.send({ createdProducts});
    } catch (error) {
      res.status(500).send(error.message)
    }
  },
module.exports = productCtrl;

我的产品。路由器:

const express = require('express');
const productCtrl = require('../controllers/productCtrl');
const productRouter = express.Router();
productRouter.get('/seed', productCtrl.sendDatasProductToMoongoose )
module.exports = productRouter;

我的服务器

require('dotenv').config();
const express = require('express');
const cors = require("cors");


// require connexion db and run it 
const connectDB = require('./config/db');
const app = express();
connectDB();

// fonct. middleware intégrée dans Express :
// Il analyse les req' entrantes avc des charges utiles JSON et est basé sur un analyseur de corps.
// parse les req http en json
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());


app.use('/api/products', require('./routes/productRouter.js'))
app.use('/api/users', require('./routes/userRouter.js'))


//Test
/* app.get('/', (req, res) => {
  res.send('Server is Ready')
}) */

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on ${PORT}`));

我对邮递员的要求: GET http://localhost:5000/api/products/seed

我的错误:E11000 重复密钥错误集合:dbname.products index:product_id_1 dup key:{product_id:null}

我的文件数据

const bcrypt = require( 'bcryptjs');

const data = {
  users: [
    {
      name: 'Nemo',
      email: 'nemo@mail.com',
      password: bcrypt.hashSync('1111', 8),
      isAdmin: true,
    },
     {
      name: 'Dori',
      email: 'dori@mail.com',
      password: bcrypt.hashSync('1111', 8),
      isAdmin: false,
    },
  ],
  products: [
    {
    name:"Pendentif Lunaire en Cristal de Swarovski",
    category: "Pendentif",
    image: '../../frontend/public/images/Moon-pendant.png',
    material:"cristal de Swarovski,  argent 925",
    price: 45,
    countInStock: 3
    },
    {
    name:"Pendentif Labradorite",
    category: "Pendentif",
    image:'../../frontend/public/images/Labradorite-pendant-big.png',
    material:"labradorite,argent 925",
    price: 80,
    countInStock: 2
    },
     {
    name:"Pendentif Labradorite",
    category: "Pendentif",
    image:'../../frontend/public/images/Labradorite-pendant-medium.png',
    material:"labradorite,argent 925",
    price: 45,
    countInStock: 3
    },
    {
    name:"Pendentif Oeil du Tigre",
    category: "Pendentif",
    image:'../../frontend/public/images/EyeTiger-pendant.png',
    material:"labradorite,argent 925",
    price: 45,
    countInStock: 3
    },
    {
    name:"Pendentif en Quartz Rose",
    category: "Pendentif",
    image: '../../frontend/public/images/Quartz-pendant.png',
    material:"améthiste, argent 925",
    price: 35,
    countInStock: 6,
  }
  ]
}

module.exports = data;

标签: javascriptreactjsmongodbexpressmongoose

解决方案


似乎“product_id”是您架构中的唯一索引,对吗?并且您正在尝试插入一个“product_id”为空值的新文档,该文档在同一索引中具有该值的现有文档。

当您在唯一索引上插入具有空值的文档时,该值将存储为 null。(我将把那部分留给文档):

如果文档在唯一索引中没有索引字段的值,则索引将为此文档存储空值。由于唯一性约束,MongoDB 将只允许一个缺少索引字段的文档。如果有多个文档没有索引字段的值或缺少索引字段,则索引构建将失败并出现重复键错误。

您可以删除 product_id 处具有空值的条目,它应该可以工作。

但我强烈建议在插入您的产品之前进行一些验证,以确保它不会再次发生。


推荐阅读