I'm currently using the mongodb driver for node.js in a web project. I found the basic functions through w3schools and the mongo docs. But I haven't found a javascript method for validation, and the only way that I can't do it right now is through the mongo shell in cmd. Is there a function to write raw code in a js so that mongo can execute it like a script? That would save a lot of time having to deal with complex validations in console.
-
What are you trying to validate?Isaac Vidrine– Isaac Vidrine2018-10-04 19:20:23 +00:00Commented Oct 4, 2018 at 19:20
-
I'm validating schemas using the validator function for mongodb shell, using validator and $jsonSchema. I'm able to do it through command line, but I wanted to see if there was a higher level implementation.David Cristerna– David Cristerna2018-10-05 16:30:11 +00:00Commented Oct 5, 2018 at 16:30
3 Answers
I would highly suggest looking into mongoose npm module. Mongoose npm module has a lot of useful features that interact with MongoDB. You mentioned validating the data, which could also be found here.. As you are setting up schemas in Mongoose, you have the option to provide in-built validation methods.
Note this code is pulled from the validation page of mongoosejs.com
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() {
return this.bacon > 3;
}
}
});
3 Comments
So it sounds like what you are looking for is Stored JavaScript. While they are not equivalent, you can think of it almost like a Stored Procedure in SQL. Here is a good introduction to Stored JavaScript.
1 Comment
If you are looking for validating the objects then you can use joi library.