Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do type checking in MongoDB?

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.

like image 997
deltanovember Avatar asked May 19 '12 13:05

deltanovember


3 Answers

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 }
like image 59
stan Avatar answered Nov 16 '22 05:11

stan


The method isValid does not exist (anymore?), your best bet is a simple regular expression, as provided here

like image 39
swaagie Avatar answered Nov 16 '22 03:11

swaagie


You could add validation to the _creator field of the schema as described here.

_creator : { type: Schema.ObjectId, ref: 'Person', validate: ... }
like image 1
JohnnyHK Avatar answered Nov 16 '22 04:11

JohnnyHK