Reputation: 6086
I have the following Mongoose schema and path validaion:
var locationSchema = new Schema({
userid: { type: Number, required: true },
location: {
type: [{
type: "String",
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
}],
coordinates: { type: [Number], required:true }
},
tags: [{ type: String, index: true, required: true }],
create_date: { type: Date, default: Date.now }
});
locationSchema.path('location.coordinates').validate(function(coordinates){
return coordinates && coordinates.toString().match(/([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/g);
}, 'Invalid latitude or longitude.');
When I start my app i get:
locationSchema.path('location.coordinates').validate(function(coordinates){
^
TypeError: Cannot call method 'validate' of undefined
Can anyone advise why this is failing? Note is I just validate path('location'), its starts fine.
Upvotes: 0
Views: 948
Reputation: 311835
To define a field in an embedded object named type
, you need to define its type using the explicit object notation or Mongoose thinks it's defining the type of the parent object instead:
var locationSchema = new Schema({
userid: { type: Number, required: true },
location: {
type: { type: [{
type: "String",
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
}]},
coordinates: { type: [Number], required:true }
},
tags: [{ type: String, index: true, required: true }],
create_date: { type: Date, default: Date.now }
});
Upvotes: 1