Mongoose - Error: 'CastError: Cast to ObjectId failed for value “{ name: 'RandomName' }” at path “authors”'

Question!

Error:
'CastError: Cast to ObjectId failed for value "{ name: 'RandomName' }" at path "authors"'

I am using post man to do a put request to a book, which I have the _id of. I am sending a body with key value pair of name: "whateverName".

The goal is for books to have many authors in an array, on a property of each book called 'authors'.

Here is the controller.

app.put("/book/update/:id", function(req, res) { var author = req.body; Book.findOneAndUpdate({_id: req.params.id}, {$push: {authors: author}}, {new: true}, function(err, book) { if (err) { console.log(err); } else { console.log("author inserted"); res.status(200).send(); } }) })

Here is the Author schema.

```

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var AuthorSchema = new Schema({
  name: String
});

module.exports = mongoose.model("Author", AuthorSchema);

```

Here is the Book schema.

```

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var BookSchema = new Schema({
  title: String,
  author: String,
  category: String,
  authors: [{type: Schema.ObjectId, ref: "Author"}]
});

module.exports = mongoose.model("Book", BookSchema);

```

Why is it giving me such a hard time on my day off? Can someone please tell me what gives? I just simply want to push a new author (which is it's own model) to a specific book using a reference.

Thanks so much :)

By : Tyler


Answers

Actually you are storing author's _id in the book authors array. So you need to pass the author data as like this [{array of _id's}]

app.put("/book/update/:id", function(req, res) {
  /***************************/
  var author = req.body; // array of _id (ObjectId)
  /***************************/
  Book.findOneAndUpdate({_id: req.params.id}, {$push: {authors: author}}, {new: true}, function(err, book) {
      if (err) {
        console.log(err);
      } else {
        console.log("author inserted");
        res.status(200).send();
      }
   })
})
By : ti2005


Solution: You've got to create the AUTHOR instance first, then inside of that function, use the return value of the author to find a book, and update it via pushing that newly created author's id to the array.

app.put("/book/update/:id", function(req, res) { Author.create(req.body, function(err, author) { Book.findOneAndUpdate({_id: req.params.id}, {$push: {authors: author._id}}, {upsert: true}, function(err, book) { if (err) { console.log(err); } else { console.log("author inserted"); res.status(200).send(); } }) }) })

By : Tyler


You are almost there. Use getent for resolving UID to username:

getent passwd `grep "^Uid" /proc/$i/status |awk '{printf "%4s",$2}'`| cut -d: -f1
By : Misko


This video can help you solving your question :)
By: admin