node.js - MongoDB/Mongoose 的 E11000 重复键错误

标签 node.js mongodb mongoose

我有一个用户模型架构、一个工作模型架构和一个批评模型架构。这些模式之间的关系是用户可以提交许多作品(例如博客文章),并且可以评论/评论(我们称之为批评)其他人的帖子(作品)。

因此,当用户提交批评(将其视为评论)时,这就是我的帖子路线。我通过 id 找到工作,然后创建一个新的批判模型对象,并将其传递给 .create() mongoose 函数。一切看起来都很顺利,直到我到达了 foundWork.critiques.push(createdCritique) 行。控制台记录错误并显示:

BulkWriteError:E11000重复键错误集合:zapper.critiques索引:username_1 dup key:{:null}

显然,它说对象中有两个用户名键,并且它们相互冲突,但我对此不够熟悉,无法找到问题的根源并在 Mongoose 模型中修复它。型号如下。如果有人可以提供帮助,我们将不胜感激。

// post route for getting the review
router.post('/:id', isLoggedIn, function(req, res) {

    Work.findById(req.params.id, function(err, foundWork) {
        if (err) {
            console.log(err);
        } else {

            // create a new critique
            var newCritique = new Critique ({
                reviewerName: {
                    id: req.user._id,
                    username: req.user.username
                },
                work: {
                    id: foundWork._id,
                    title: foundWork.title
                },
                critique : req.body.critique,
                date: Date.now(),
                rating: 0
            });

            // save new critique to db
            Critique.create(newCritique, function(err, createdCritique) {
                if (err) {
                    console.log(err)
                } else {
                    console.log("Created critique is ");
                    console.log(createdCritique);

                    // push the new critique into array of critiques of the work
                    foundWork.critiques.push(createdCritique);
                    // save to db
                    foundWork.save();                                
                }
            });
        }
    });

用户模型:

var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');

var UserSchema = new mongoose.Schema({
    firstname: String,
    lastname: String,
    username: String,
    password: String,
    email: String,
    zip: String,
    bio: {
        type: String,
        default: ''
    },
    influences: {
        type: String,
        default: ''
    },
    favBooks: {
        type: String,
        default: ''
    },
    notWriting: {
        type: String,
        default: ''
    },
    favHero: {
        type: String,
        default: ''
    },
    favVillain: {
        type: String,
        default: ''
    },
    works: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Work'
        }
    ],
    critiques: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Critique'
        }
    ],
    friends: [
        {
            friendId: String,
            friendName  : String,
            friendPic: String
        }
    ],
    friendRequests: [
        {
            sendingFriendId: String,
            sendingFriendName  : String,
            sendingFriendPic: String
        }
    ],
    createdDate: {
        type: Date,
        default: Date.now
    },
    lastLogin: {
        type: Date,
        default: Date.now
    }
});

UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

工作模式:

var mongoose = require('mongoose');

var WorkSchema = new mongoose.Schema({
    title: String,
    genre: String,
    workType: String,
    length: Number,
    ageRange: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    },
    manuscriptText: String,
    critiques: [ 
        {
            id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Critique"
            }
        }
    ],
    ratingNumber: [Number],
    ratingSum: {
        type: Number,
        default: 0
    },
    date: {
        type: Date,
        default: Date.now
    },
    isPublic: {
        type: Boolean,
        default: true
    }
});


module.exports = mongoose.model("Work", WorkSchema);

批评模型:

var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');

var CritiqueSchema = new mongoose.Schema({
    reviewerName: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    },
    work: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Work"
        },
        title: String
    },
    critique: String,
    date: {
        type: Date,
        default: Date.now
    },
    rating: [Number]
});


CritiqueSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Critique", CritiqueSchema);

最佳答案

当您在 MongoDB 中创建唯一索引时,默认行为是它也会索引空值。

这意味着,如果您的集合中有一个用户名为 null 的文档,则无法添加另一个用户名为 null 的文档。

您需要的是 a sparse index它仅索引实际值(并忽略该字段为 null 的文档)。

Check this link它展示了如何在 mongoose 中创建稀疏索引与“正常”索引(索引:true,与备用:true)。大多数时候您需要稀疏索引。

关于node.js - MongoDB/Mongoose 的 E11000 重复键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125210/

相关文章:

node.js - 在建立安全 TLS 连接之前,客户端网络套接字已断开 aws lambda nodejs

node.js - Node Heroku 部署找不到导出的 Mongo 架构

mongodb - 如果slice存在,并且它包含至少一个设置为true的特定变量

node.js - 具有多个 foreignFields 的 Mongoose 虚拟

javascript - 改变函数参数

javascript - 如何添加导入快捷方式 - 别名

mongodb - Mongodb查询优化

node.js - MongoDB:如何将嵌套数组分组到一个文档中?

javascript - 如何从 Mongoose 查询回调中访问特定值?

Node.JS + Mongoose 回调 hell