Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store URL value in Mongoose Schema?

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 }
})
like image 517
Source Avatar asked Nov 06 '17 10:11

Source


3 Answers

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
}
});
like image 111
Mahmoud Ibrahim Avatar answered Nov 19 '22 13:11

Mahmoud Ibrahim


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.');
like image 41
Nadun Kulatunge Avatar answered Nov 19 '22 12:11

Nadun Kulatunge


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

like image 45
Vivek Ghanchi Avatar answered Nov 19 '22 11:11

Vivek Ghanchi