Answer the question
In order to leave comments, you need to log in
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)
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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question