乐闻世界logo
搜索文章和话题

How to store URL value in Mongoose Schema?

1个答案

1

Storing URL values in Mongoose is a relatively straightforward process, which can be achieved by defining a field with a String type. To ensure that stored URLs conform to a standard format, we can use custom validators within the Mongoose Schema or leverage existing npm packages to validate URL formats.

Here is a basic example demonstrating how to define and validate a URL field within a Mongoose Schema:

javascript
const mongoose = require('mongoose'); const urlSchema = new mongoose.Schema({ website: { type: String, required: [true, 'Website URL is required'], validate: { validator: function(v) { // Use a regular expression to validate the URL format return /^(https?:\/\/)?([\da-z\.-]+)\.( [a-z\.]{2,6})([\/\w \.-]*)*\/?$/.test(v); }, message: props => `${props.value} is not a valid URL!` } } }); const MyModel = mongoose.model('MyModel', urlSchema); // Create an instance to test const item = new MyModel({ website: 'https://www.example.com' }); item.save(function(err) { if (err) { console.error(err); } else { console.log('Website URL is saved successfully!'); } });

In this example, we define a field named website that is required and includes a custom validator, which uses a regular expression to check if the URL is valid. If the URL does not conform to the specified format, the validator returns an error message.

Additionally, if you wish to simplify the validation process using third-party libraries, consider using npm packages such as validator. validator is a string validation library that provides various preset validation methods, including URL validation:

javascript
const mongoose = require('mongoose'); const validator = require('validator'); const urlSchema = new mongoose.Schema({ website: { type: String, required: [true, 'Website URL is required'], validate: [validator.isURL, 'Please provide a valid URL'] } }); const MyModel = mongoose.model('MyModel', urlSchema); // Create an instance to test const item = new MyModel({ website: 'https://www.example.com' }); item.save(function(err) { if (err) { console.error(err); } else { console.log('Website URL is saved successfully!'); } });

In this example, we use validator.isURL as the validation function, which checks if the input string is a valid URL. This simplifies the code and makes it easier to maintain and understand.

2024年6月29日 12:07 回复

你的答案