@EmKotlety

Почему не работает связь один ко многим mongoose express?

Связь один ко многим не работает: у Posts есть один owner. У User(owner) может быть много постов.. В бд массива постов у User почему то не видно, показывает пустой array
Модель Posts:
const {Schema, model, Types} = require('mongoose')
const schema = new Schema({
    title: {type: String,
    required: true, unique: true
    },
    discription: {type: String,
    required: true, unique: true},
    owner: {type: Types.ObjectId, ref: 'User'}
})
module.exports = model('Posts', schema)

Модель User:
const {Schema, model, Types} = require('mongoose')
const schema = new Schema({
    email: {type: String,
    required: true, unique: true
    },
    password: {type: String, required: true},
    login:{type: String, required: true},
    posts: [{type: Types.ObjectId, ref: 'Posts'}],
    isActivated: {type: Boolean, default: false},
    activationLink: {type: String},
    googleId: {type: String}
})
module.exports = model('User', schema)

Роут:
router.post('/create', authMiddleWare,
 async (req, res) => {
    try {
         const user = await User.findOne({_id: req.user.id })
        const { title, discription } = req.body
        console.log('запрос', req.body)
        console.log('значения', title, discription)
        const post = new Posts({title, discription, owner: req.user.id});
        await post.save()
        return res.status(201).json({            
            post,
            user: {
                id: user.id,
                email: user.email,
                title,
                discription
            },
            message: 'новый пост создан'
        })
    }
    catch (e) {
        console.log(e)
        res.send({ message: "Server error" })
    }
})

Вот так выглядит БД постов
_id:610628398602511e786e08d6
title:"111111111111"
discriptiотображалисьon:"11111111111111111"
owner:61370b4f64565c259871bb5d
__v:0

А у пользователя с id как у owner пустой массив. Получается что если обратиться к этому юзеру , то постов у его нет. Как сделать так чтобы в БД они
  • Вопрос задан
  • 118 просмотров
Пригласить эксперта
Ваш ответ на вопрос

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

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