2

I'm getting error whenever I'm trying to save into my database a document with this schema:

var schemaForBooks = new Schema({
    book: String,
    author: String,
    who_has_this: Object,
    points: Number,
    upvoted_by_users: [Schema.Types.ObjectId],
    downvoted_by_users: [Schema.Types.ObjectId]
});

Rest all is good, but putting anything into upvoted_by_users or downvoted_by_users, I get this error:

[ERROR] Trace- CastError: Cast to [ObjectId] failed for value "[{"userName":"Vibhu","userId":"3833d1g870feaf4a38723"}]" at path "upvoted_
by_users"

I'm pretty sure I'm doing something wrong with the schema itself, but I don't know what.

Any help would be appreciated.

2
  • {"userName":"Vibhu","userId":"3833d1g870feaf4a38723"}, is this what you're placing in the array? Commented Jun 11, 2017 at 16:46
  • Yes, I wanted to do that, but now I know, I'll have to create a nested Schema for that. I was too dumb here. Commented Jun 15, 2017 at 4:42

1 Answer 1

1

The error says that you're trying to cast the following array of object {"userName":"Vibhu", "userId":"3833d1g870feaf4a38723"} to an array of ObjectId.

So, you need to get rid of the userName field, so you can turn your array of String + ObjectId to an array of ObjectId.

You can do it with the Array#map method on your js Array, for example :

var arr = [{"userName":"Vibhu","userId":"3833d1g870feaf4a38723"}];
var myCorrectArr = arr.map(field => field.userId);

Hope it helps,
Best regards,

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @boehm_s, your reply didn't directly answered my query but got me to that. I was confusing ObjectId with some generic Object object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.