Mongoose: CastError: сбой приведения к ObjectId для значения «Object» в пути «property» - PullRequest
0 голосов
/ 06 июня 2019

Я получаю сообщение об ошибке:

CastError: Cast to ObjectId failed for value "{ Type: 'Idea',
'Field/s of idea': 'cs',
Idea: 'cs',
Date: 2019-06-06T11:23:34.010Z }" at path "posts"

Я пытаюсь обновить свойство "posts" документа с помощью объекта, который не содержит поля для ObjectId.У документа уже есть _id, установленный в ObjectId.Я не знаю, почему возникает такая ошибка, когда я не пытаюсь добавить Object Id.Я искал ошибку, и проблемы были связаны только со свойством _id, имеющим неправильный ObjectId.

вот мой код:

User.findOne({email: req.user.email})
        .then(user=>{
            if(user.posts){
                user.posts.push({
                        "Type": "Idea",
                        "Field/s of idea": req.body["Field/s of idea"],
                        "Idea": req.body.idea,
                        "Date": new Date()
                        });
            }else{
                user.posts = [{
                        "Type": "Idea",
                        "Field/s of idea": req.body["Field/s of idea"],
                        "Idea": req.body.idea,
                        "Date": new Date()
                        }];
            };
            console.log(user);
            user.save();
            res.send(user);
            console.log(req.user)
        })
        .catch(err=>{
            if(err)throw err;
        });

Мой код схемы:

const UserSchema = new Schema({
    _id: {type: ObjectId, auto: true},
    username: {type: String, required: true, max:18},
    email: {type: String, required: true},
    password: {type: String, required: true, min:5},
    date_of_registration: {type: Date, required: true},
    posts: [ Schema.Types.ObjectId ]
}, { strict: false });
...