如何在Mongoose Schema中存储URL值?

时间:2017-11-06 10:20:02

标签: node.js mongodb mongoose mongoose-schema

我正在将图片从IOS应用程序上传到Firebase,后者向我返回包含URL类型网址的元数据。

我应该在数据库中存储String类型,如下面的代码吗?或URL s的具体类型?

var schema = new Schema({
  downloadURL: { type: String, createdDate: Date.now }
})

3 个答案:

答案 0 :(得分:5)

嗯,根据docs Monngoose没有URL的架构类型。您可以使用带有RegExp的字符串来验证它或使用某些自定义类型,如this one

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

var UserSchema = new mongoose.Schema({
url: {
    work: mongoose.SchemaTypes.Url,
    profile: mongoose.SchemaTypes.Url
}
});

答案 1 :(得分:0)

猫鼬没有URL架构,您可以使用mongoose-Validator

存储在String中并进行验证

这是它的语法

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

希望这会对您有所帮助

答案 2 :(得分:0)

您可以使用正则表达式来验证网址,

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.');
相关问题