【问题标题】:How to store URL value in Mongoose Schema?如何在 Mongoose Schema 中存储 URL 值?
【发布时间】:2018-04-18 11:28:34
【问题描述】:

我正在将图像从 IOS 应用程序上传到 Firebase,Firebase 会向我返回元数据,包括 URL 类型的 URL。

我应该像下面的代码那样将String 类型的它存储在数据库中吗?或者URLs 有特定的类型?

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

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    好吧,根据 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
    }
    });
    

    【讨论】:

    • 如果有人使用 'ES module' 而不是 'commonjs' 怎么办?
    【解决方案2】:

    您可以像这样使用正则表达式来验证 URL,

    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 没有 URL 架构,您可以存储在字符串中并使用 mongoose-Validator 进行验证

      这是它的语法

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

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-25
        • 2021-02-25
        • 1970-01-01
        • 2020-04-10
        • 2012-07-14
        • 2017-10-31
        • 1970-01-01
        • 2015-11-26
        相关资源
        最近更新 更多