How to store URL value in Mongoose Schema?

淺唱寂寞╮ 提交于 2021-02-18 11:45:08

问题


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

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



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



回答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



来源:https://stackoverflow.com/questions/47134609/how-to-store-url-value-in-mongoose-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!