@Bredy

Не получается создать больше двух постов. E11000 duplicate key error collection: myFirstDatabase.posts index: text_1 dup key: { text: null }?

Cделал валидацию для нового поста.

export const postCreateValidation = [
    body('title', 'неверный формат заголовка').isLength({min: 5}), 
    body('description', 'длина пароля должны быть не менее 5 символов').isString().isLength({min: 10}), 
    body('tags',  'укажите массив').isString().optional(),
    body('imageURL', 'неверная ссылка').isString().optional()
]


Проверка на авторизацию пользователя при создании поста.

export const createPost = async (req, res) => {
        try {
            const doc = new PostModel({
                title: req.body.title,
                description: req.body.description,
                tags: req.body.tags,
                imageUrl: req.body.imageUrl,
                userId: req.userId,
            });
            const post = await doc.save();
            res.json(post);

        } catch(err) {
            console.log(err)
            res.status(500).json({
                message: ' не удалось создать пост'
            })
        }
}


Так же есть модель для поста.

const PostSchema = new mongoose.Schema({
    title:{
        type:String,
        require: true,
        unique: true,
    },
    description: {
        type: String,
        require: true,
        unique: true,
    },
    tags:{
        type: Array,
        default:[],
    },
    viewsCount: {
        type:Number,
        default: 0,
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        require:true,
    },
    imageUrl:String, 
}, {
    timestamps: true, 
});


Функция для создания нового поста.

export const createPost = async (req, res) => {
        try {
            const doc = new PostModel({
                title: req.body.title,
                description: req.body.description,
                tags: req.body.tags,
                imageUrl: req.body.imageUrl,
                userId: req.userId,
            });
            const post = await doc.save();
            res.json(post);

        } catch(err) {
            console.log(err)
            res.status(500).json({
                message: ' не удалось создать пост'
            })
        }
}


При создании первого поста все добавляется, но при создании второго вылетает ошибка в консоль.
Так и не понял при чем тут text: null.

MongoServerError: E11000 duplicate key error collection: myFirstDatabase.posts index: text_1 dup key: { text: null }


добавляю пост по типу

{
      title: "#3sd",
      description: "xzsadasdaasdcz ",
      tags: ["sasdsd", "asdsds", "dssdsd"],
      imageURL: "https://kartinkof.club/uploads/posts/2022-05/1653102447_23-kartinkof-cl26.jpg"
}
  • Вопрос задан
  • 32 просмотра
Пригласить эксперта
Ответы на вопрос 1
@Bredy Автор вопроса
At the first i created post with body:

{
"title": "",
"text": "",
"tags": ["sad", "asjkldss", ""],
"imageURL": ""

}
title and text is unique and their index save in mongobd.
Than i changed body

{
"title": "",
"description": "",
"tags": ["sad", "asjkldss", ""],
"imageURL": ""

}
And i needed to delete unique saved index and it's working. i deleted in mongoDB compass
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы