Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Mongoose Actually Validate the Existence of An Object Id?

I like the validation that comes with Mongoose. We are trying to figure out whether we want to use it, and put up with the overhead. Does anyone know if providing a reference to the parent collection when creating a mongoose schema, (in the child schema, specify the object id of the parent object as a field,) does this then mean that every time you try to save the document it checks the parent collection for the existence of the refereneced object id?

like image 519
CargoMeister Avatar asked Aug 29 '13 16:08

CargoMeister


People also ask

How do you check if the object ID is valid or not?

isValidObjectId() is most commonly used to test a expected objectID, in order to avoid mongoose throwing invalid object ID error. if (mongoose. isValidObjectId("some 12 byte string")) { return collection. findOne({ _id: "some 12 byte string" }) // returns null if no record found. }

Does Mongoose have built in validation?

Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.

What is object ID in Mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.


1 Answers

I'm doing it with middleware, performing a search of the element on validation:

ExampleSchema = new mongoose.Schema({

    parentId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Example'
    }

});

ExampleModel = mongoose.model('Example', ExampleSchema);

ExampleSchema.path('parentId').validate(function (value, respond) {

    ExampleModel.findOne({_id: value}, function (err, doc) {
        if (err || !doc) {
            respond(false);
        } else {
            respond(true);
        }
    });

}, 'Example non existent');
like image 193
fernandopasik Avatar answered Oct 31 '22 00:10

fernandopasik