首页 > 解决方案 > 无法在 mongoDB 中创建唯一索引

问题描述

const popupSchema = new mongoose.Schema(
    {
        /**
         * @type schema field / ObjectId
         * @description User whose popus are stored.
         * @note should be required
         */

        user_id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
            required:true,
            index: { unique: true }
        },
        /**
         * @type schema field / Array
         * @description Information of all the popups of the User.
         */

        popupsArray: [popupDetails]
    },
    opts
);

这是我的架构,我想让 user_id 成为 unique_index。架构中没有其他具有相同 user_id 的条目。我正在运行此脚本以实现相同的目的:

await popups
    .createIndexes(
        {user_id:1}
    )
    .then(res => {
            console.log("done")
        }
    ).catch((err)=>{
        console.log("error in indexing popups",err)
    })

但是此脚本以错误终止=>
名称索引:user_id_1 已存在不同的选项。{ 好的:0,代码:85,代码名称:'IndexOptionsConflict'}

如何使 user_id 唯一索引?我也在 user_id 中尝试了 required:true 但它不起作用。

required:true在运行此脚本之前添加了。这会有什么不同吗?

标签: javascriptmongodbmongoosemongodb-querymongoose-schema

解决方案


推荐阅读