Hello,
I am working on the Personal Library project for the Quality Assurance certificate. I’m currently working on posting a comment for a book and am using the findByIdAndUpdate()
Mongoose method. After successfully updating the comments
property in my document, I thought it would be best to also update the commentcount
property inside the same method. However, doing this returns the following CastError:
CastError: Cast to Number failed for value "{ '$size': '$comments' }" (type Object) at path "commentcount"
Book Schema
require('dotenv').config();
const mongoose = require('mongoose');
const bookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
comments: {
type: [String],
default: []
},
commentcount: {
type: Number,
default: 0
}
});
const Book = new mongoose.model('Book', bookSchema);
//**********EXPORTS**************
exports.Book = Book;
API
app
.route("/api/books/:id")
.post(async (req, res) => {
let bookId = req.params.id;
let comment = req.body.comment;
if (comment) {
console.log(`COMMENT: ${comment}`)
try {
let book = await Book.findByIdAndUpdate(
bookId,
{
$push: {comments: comment},
$set: {commentcount: {$size: '$comments'}},
},
{new: true},
);
console.log(book);
return book ? res.json(book) : res.send("no book exists");
} catch (err) {
console.error(err);
return res.send("no book exists");
}
} else {
return res.send("missing required field comment");
}
})
Does anyone know why I’m catching the CastError and a possible workaround?
P.S. I know that I can just push the new comment to the document, then use the returned, updated book to set commentcount
to the comments
length, and then do book.save()
, but I would like to figure out why it is not working using the $set
operator with $size
.