Mongoose Cast to ObjectId failed for value

时间:2016-08-31 17:12:43

标签: node.js mongodb mongoose

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: Date.now },
  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

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

    Review.findOneAndUpdate(query, update, options, function (err, doc) {
        console.log(err);
        res.end("done");
    });
});

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"',

1 个答案:

答案 0 :(得分:4)

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 req.body.email, then make your update { $push: { voters: userId } } (where userId is the id of the User you found).