E
E
EmKotlety2021-10-20 06:00:03
Mongoose
EmKotlety, 2021-10-20 06:00:03

Why doesn't mongoose express one-to-many communication work?

One-to-many relationship doesn't work: Posts have one owner.
User(owner) can have many posts. For some reason, the User(owner) has an empty array of posts. The Posts model shows an empty array :

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 model:
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)

Route:
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" })
    }
})

This is what the post database looks like
_id:610628398602511e786e08d6
title:"111111111111"
discriptiотображалисьon:"11111111111111111"
owner:61370b4f64565c259871bb5d
__v:0

And the user with id as owner has an empty array. It turns out that if you turn to this user, then he has no posts. How to make it so that they are in the database

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question