The example here
http://mongoosejs.com/docs/populate.html
Provides the following code
var story1 = new Story({
title: "A man who cooked Nintendo"
, _creator: aaron._id
});
_creator is defined above as follows
_creator : { type: Schema.ObjectId, ref: 'Person' }
If I modify the code to the following
var story1 = new Story({
title: "A man who cooked Nintendo"
, _creator: {name: 'test'}
});
It seems to happily insert the data into MongoDB.
{ "title" : "A man who cooked Nintendo", "_creator" : { "name" : "test" }, "_id" : ObjectId("4fb7a55315c5f2de07000002"), "fans" : [ ] }
How would I catch the error before insertion? I would like to check that it is not only an ObjectId but also that it corresponds to a valid Person.
To continue what @JohnnyHK proposed, here is a complete solution(assuming _creator is a reference to a numeric id).
If you want to check if the value is a valid ObjectId
function isObjectId(n) {
return mongoose.Types.ObjectId.isValid(n);
}
validate: [validator, 'my error type']
_creator : { type: Schema.ObjectId, ref: 'Person', validate: isObjectId }
The method isValid does not exist (anymore?), your best bet is a simple regular expression, as provided here
You could add validation to the _creator field of the schema as described here.
_creator : { type: Schema.ObjectId, ref: 'Person', validate: ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With