How to store URL value in Mongoose Schema?

Solution 1

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
}
});

Solution 2

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.');

Solution 3

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

Share:
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin 2 months