【问题标题】:MongoDB E11000 duplicate key error collection with no unique field in schemaMongoDB E11000 重复键错误集合,架构中没有唯一字段
【发布时间】:2021-07-10 01:09:56
【问题描述】:

我正在设置一个简单的博客表单,其中包含标题、内容和json base64 图像数据以传递到本地 MongoDB 服务器。这是我的发帖路线:

router.post('/:userName/posts/new', isAuthenticated, async (req, res) => {
    let parsedImage = req.body.file != null && req.body.file != '' ? JSON.parse(req.body.file).data : ''

    const newPost = new Post({
        title: req.body.title,
        content: req.body.content,
        imageJson: parsedImage
    })

    try {
        await newPost.save()
        res.redirect("/account")
    } catch (e) {
        console.log(e)
        res.redirect("/home")
    }
})

这是我的模式模型:

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    content: {
        type: String,
        required: true,
    },
    imageJson: {
 

           type: String
        }
});
    
    module.exports = mongoose.model('Post', postSchema)

如您所见,没有unique: true。我第一次尝试运行它时,它运行完美,直接重定向到 /account 页面,正如 try catch 块中所预期的那样。但是,在第二次尝试时,使用不同的图像、不同的内容和不同的标题,它抛出了这个错误:

MongoError: E11000 duplicate key error collection: fullstacksus.posts index: userName_1 dup key: { userName: null }

我不知道发生了什么,因为 userName 是在我的用户帐户 route 中使用的数据库名称,但不是在我的帖子制作 route 中使用的数据库名称。为什么又出现了?感谢您的回答。

【问题讨论】:

  • db.posts.getIndexes() 显示什么?
  • 显示:[ ]

标签: node.js database mongodb mongoose unique


【解决方案1】:

在您的 MongoDB 中,{userName: 1} 上有一个唯一索引。由于您的架构没有 userName 字段,因此每个文档中都缺少它,即 null,因此索引会拒绝它。

使用 mongo shell 连接和删除索引。

【讨论】:

  • 如何删除索引?我不需要用户名上的唯一参数
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 2021-09-19
  • 2021-03-04
  • 1970-01-01
  • 2018-10-12
相关资源
最近更新 更多