Reputation: 1291
Well, I see that here are a few posts like this, but they didn't help me ...
let me describe my problem:
I have two Schema's
var A = new Schema({
someAttribut: {type: String},
b: {type: ObjectId, ref:'B'}
});
var B = new Schema({
someAttribut2: {type: Boolean, 'default': false'}
});
Now I'm in the situation that I already have a B-Object and I want to create an A-Object.
So i do it this way:
var a = new A(req.aFromClient); // {_id:null, someAttribute:'123', b:null}
//load b from Database ...
a.b = existingBFromDatabase; // {_id: 'Sb~Õ5ÙÐDâb', someAttribute2: false}
The b object is loaded from my monogDB. The debugger shows me a valid ObjectId (53627ed535d9d04416e26218 or Sb~Õ5ÙÐDâb) for my b .
But when I save my new A-Object, i get the error: 'CastError: Cast to ObjectId failed for value "" at path "_id"'
I don't understand why I get this error. Firstly, I don't define the id in the schema, so mongoose should add it, which seems to work. Secondly, I think that mongoose should generate a new ID when I create an a object.
do you have any proposal?
Upvotes: 1
Views: 8052
Reputation: 2750
You should do:
a.b = existingBFromDatabase._id;
Because mongoose only works with the id of the already existing object.
Upvotes: 0
Reputation: 311835
Based on the comment in the code, _id
does have a value (of null
). So you need to remove _id
from req.aFromClient
before creating your new A
doc from it:
delete req.aFromClient._id;
var a = new A(req.aFromClient);
Upvotes: 1