7

I am uploading the images from an IOS application to Firebase which returns to me the metadata including the URL of type URL.

Should I store it of type String in the database like below code? or there is specific type for URLs?

var schema = new Schema({
  downloadURL: { type: String, createdDate: Date.now }
})
Source
  • 99
  • 1
  • 1
  • 7

3 Answers3

9

Well, As per the docs Monngoose doesn't have a schema type for URL. You could just use a string with RegExp to validate it or use some custome made type like this one

var mongoose = require('mongoose');
require('mongoose-type-url');

var UserSchema = new mongoose.Schema({
url: {
    work: mongoose.SchemaTypes.Url,
    profile: mongoose.SchemaTypes.Url
}
});
Mahmoud Ibrahim
  • 1,703
  • 15
  • 15
7

Mongoose does not have schema for URL, you can store in String and Validate using mongoose-Validator

Here is the syntax for it

validate: { 
  validator: value => validator.isURL(value, { protocols: ['http','https','ftp'], require_tld: true, require_protocol: true }),
  message: 'Must be a Valid URL' 
}

Hope this will Help you

Vivek Ghanchi
  • 232
  • 4
  • 16
7

You can use Regex to Validate the URL like this,

const mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
    downloadURL: {
        type: String,
        required: 'URL can\'t be empty',
        unique: true
    },
    description: {
        type: String,
        required: 'Description can\'t be empty',
    }
});

userSchema.path('downloadURL').validate((val) => {
    urlRegex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
    return urlRegex.test(val);
}, 'Invalid URL.');
Nadun Kulatunge
  • 1,567
  • 2
  • 20
  • 28