geek geek - 1 year ago 259
Node.js Question

Mongoose Cast to ObjectId failed for value

I have following schema in mongoose

var mongoose = require("mongoose");

var Schema = mongoose.Schema;
var UserSchema = new mongoose.Schema({
email: { type: String, unique: true },

var User = mongoose.model('User', UserSchema);
var ReviewSchema = new Schema({
schoolId: String,
firstname: String,
image_url: String,
lastname: { type: String },
email: String,
rating: Number,
review: String,
time: { type: Date, default: },
updated_at: Date,
voters: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]


var Review = mongoose.model('Review', ReviewSchema);

module.exports = Review;

and following code in nodejs"/like", function (req, res) {
var query = { id: mongoose.Types.ObjectId( };
var voter = { email: };
var update = { $push: { 'voters': voter } };
var options = { upsert: true, 'new': true };

Review.findOneAndUpdate(query, update, options, function (err, doc) {

When I am sending request to above method I am getting following error message

{ [CastError: Cast to ObjectId failed for value "[object Object]" at path "voters"]
message: 'Cast to ObjectId failed for value "[object Object]" at path "voters"',

Answer Source

You have voters defined as an ObjectId ref, but you're trying to store an actual User representation inside it.

Assuming I understand your links correctly, you'll want to lookup the _id of the User by, then make your update { $push: { voters: userId } } (where userId is the id of the User you found).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download