'How to correctly save references to mongodb from request
I want to save data and references of child document into parent document from request, I have managed to achieve that, but I am not sure is this correct way of doing it. I have found in stackoverflow that first we have to save child document. so we can save references of child document into parent document
This is my structure of request
"category": "movie",
"overview": "This is overview",
"poster_path": "https://image.tmdb.org/t/p/w500/aWeKITRFbbwY8txG5uCj4rMCfSP.jpg",
"release_date": "2021-12-01",
"title": "Sing 2",
"vote_average": 8.2,
"cast": [
{
"name": "Matthew McConaughey",
"profile_path": "wJiGedOCZhwMx9DezY8uwbNxmAY.jpg"
},
{
"name": "Reese Witherspoon",
"profile_path": "6Pp3BrY2JbJg77Po8NOBO6zOA8m.jpg"
}
]}
//Show Schema
const showSchema = new Schema({
title: {
type: String,
unique: true,
required: [true, 'Title can not be empty.'],
trim: true,
text: true
},
slug: String,
poster_path: {
type: String,
required: [true, 'Cover can not be empty.'],
trim: true
},
overview: {
type: String,
required: [true, 'Description can not be empty.'],
trim: true,
text: true
},
release_date: {
type: Date,
default: Date.now(),
required: [true, 'Release date can not be empty.']
},
category: {
type: String,
trim: true,
required: [true, 'Please provide category']
},
vote_average: {
type: Number,
min: [1, 'Rating must be 1 or above 1'],
max: [10, 'Rating must be 10 or below 10']
},
vote_count: {
type: Number,
default: 0
},
cast: [
{
type: mongoose.Schema.ObjectId,
ref: 'Cast'
}
]
})
//Create slug
showSchema.pre('save', function(next) {
this.slug = slugify(this.title, {lower: true})
next()
})
showSchema.pre(/^find/, function (next) {
this.populate({
path: 'cast',
select: '-__v'
})
next()
})
//Cast Schema
const castSchema = new Schema({
name: {
type: String,
trim: true,
text: true,
unique: true,
required: [true, 'Please provide name of actor']
},
profile_path: {
type: String
}
})
And this is how I did it
exports.add = async (req, res) => {
const show = {
category: req.body.category,
overview: req.body.overview,
poster_path: req.body.poster_path,
release_date: req.body.release_date,
title: req.body.title,
vote_average: req.body.vote_average,
}
try {
Cast.insertMany(req.body.cast, function(error, createdCast){
if(error){
console.log('Cast', error)
return
}
Show.create(show, function(error, createdShow){
if(error){
console.log('Show', error)
return
}
createdCast.forEach(element => {
createdShow.cast.push(element._id)
});
createdShow.save(function(error, show){
if(error){
return
}
console.log('saved Show', show)
})
})
})
} catch (error) {
console.log(error)
res.status(400).json({
message: 'fail',
error: error
})
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
