I get "bookid not found" from my code. I can add author and titles separately using postman but I can't seem to get the reviewsCreate function to to work, am I missing something? PLS help
my schema
var mongoose = require('mongoose');
var reviewSchema = new mongoose.Schema({
author: {
type: String,
required: true
},
rating: {
type: Number,
required: true,
min: 0,
max: 5
},
reviewText: { type: String, required: true },
createdOn: {
type: Date,
"default": Date.now
}
});
var titleSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
favouredBy: {
type:[String],
required: false
},
reviews: [reviewSchema]
});
var bookSchema = new mongoose.Schema({
bookAuthor: {
type: String,
required: true
},
titles: [titleSchema]
});
mongoose.model('Book', bookSchema);
router.post('/books/:bookid/titles/:titleid/reviews',ctrlReviews.reviewsCreate);
module.exports.reviewsCreate = function(req, res) {
if (req.params.bookid) {
Bok
.findById(req.params.titleid)
.select('titles')
.exec(
function(err, book) {
if (err) {
sendJSONresponse(res, 400, err);
} else {
doAddReview(req, res, book);
}
}
);
} else {
sendJSONresponse(res, 404, {
"message": "Not found, bookid required"
});
}
};
var doAddReview = function(req, res, book, author) {
if (!book) {
sendJSONresponse(res, 404, "bookid not found");
} else {
book.reviews.push({
author: author,
rating: req.query.rating,
reviewText: req.query.reviewText
});
book.save(function(err, book) {
var thisReview;
if (err) {
sendJSONresponse(res, 400, err);
} else {
updateAverageRating(book._id);
thisReview = book.reviews[book.reviews.length - 1];
sendJSONresponse(res, 201, thisReview);
}
});
}
};
this is what i get when i used your recommendation error :
TypeError: Cannot read property 'push' of undefined
when i put console.log(book); right under the doAddrivew function.
{ _id: 58dd21c3cb77090b930b6063,
titles:
[ { title: 'this is title',
_id: 58dd3f2701cc081056135dae,
reviews: [],
favouredBy: [Object] },
{ title: 'this is the second tittle',
_id: 58dd42a59f12f110d1756f08,
reviews: [],
favouredBy: [Object] } ]
}