问题
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 URL
s?
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