npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

slugify-mongodb

v1.1.0

Published

A lightweight library for generating URL-friendly slugs and ensuring their uniqueness in MongoDB.

Downloads

20

Readme

slugify-mongodb

A library to generate URL-friendly slugs and ensure their uniqueness in MongoDB.

Table of Contents

Installation

Install via npm:

npm install slugify-mongodb

Usage

slugify-mongodb can be used in both CommonJS and ES Modules formats. Below are examples for both.

CommonJS

// Import the module from slugify-mongodb
const slugifyMongoDB = require('slugify-mongodb');

// Convert text to a slug
const slug = slugifyMongoDB.slugify('My Example Text');
console.log(slug); // Output: 'my-example-text'

// Generate a unique slug for a MongoDB document
const mongoose = require('mongoose');
const ExampleModel = mongoose.model('Example', new mongoose.Schema({ slug: String }));

async function createUniqueSlug(text) {
  const uniqueSlug = await slugifyMongoDB.generateUniqueSlug(text, ExampleModel);
  console.log(uniqueSlug); // Output: 'my-example-text' or 'my-example-text-1' if the slug exists
}

createUniqueSlug('My Example Text');

ES Modules

// Import the functions from slugify-mongodb
import { slugify, generateUniqueSlug } from 'slugify-mongodb';

// Convert text to a slug
const slug = slugify('My Example Text');
console.log(slug); // Output: 'my-example-text'

// Generate a unique slug for a MongoDB document
import mongoose from 'mongoose';
const ExampleModel = mongoose.model('Example', new mongoose.Schema({ slug: String }));

async function createUniqueSlug(text) {
  const uniqueSlug = await generateUniqueSlug(text, ExampleModel);
  console.log(uniqueSlug); // Output: 'my-example-text' or 'my-example-text-1' if the slug exists
}

createUniqueSlug('My Example Text');

API

slugify

Converts a string into a URL-friendly slug by lowercasing, trimming, and replacing spaces and non-word characters with hyphens.

Signature

slugify(text: string): string

Parameters

  • text (string): The text to convert to a slug.

Returns

  • (string): A URL-friendly slug.

Example

const slug = slugify('Hello World!');
console.log(slug); // Output: 'hello-world'

generateUniqueSlug

Generates a unique slug by checking for existing slugs in a MongoDB collection. If a conflict is found, appends a numeric suffix to ensure uniqueness.

Signature

generateUniqueSlug(text: string, Model: mongoose.Model): Promise<string>

Parameters

  • text (string): The text to convert to a slug.
  • Model (mongoose.Model): The Mongoose model to check for existing slugs.

Returns

  • (Promise): A unique URL-friendly slug.

Example

const mongoose = require('mongoose');
const ExampleModel = mongoose.model('Example', new mongoose.Schema({ slug: String }));

async function createUniqueSlug(text) {
  const uniqueSlug = await generateUniqueSlug(text, ExampleModel);
  console.log(uniqueSlug); // Output: 'hello-world' or 'hello-world-1' if 'hello-world' exists
}

createUniqueSlug('Hello World!');

Options

The slugify function accepts an options object to customize its behavior. If no options are provided, default values will be used.

Default Behavior

  • separator (default: '-')
  • lower (default: true)
  • preserveCase (default: false)
  • maxLength (default: Infinity)
  • reservedWords (default: [])

Custom Options

const slug = slugify('My Example Text', {
  separator: '_',
  preserveCase: true,
  maxLength: 15,
});
console.log(slug); // Output: 'My_Example_Text'

Advanced Features

Custom Separator

const slug = slugify('My Example Text', { separator: '_' });
console.log(slug); // Output: 'my_example_text'

Preserve Case

const slug = slugify('My Example Text', { preserveCase: true });
console.log(slug); // Output: 'My-Example-Text'

Maximum Length

const slug = slugify('My Example Text', { maxLength: 10 });
console.log(slug); // Output: 'my-exampl'

Reserved Words

const slug = slugify('admin', { reservedWords: ['admin', 'root'] });
console.log(slug); // Output: 'admin-<timestamp>'

Generating Unique Slugs

const uniqueSlug = await generateUniqueSlug('My Example Text', ExampleModel);
console.log(uniqueSlug); // Output: 'my-example-text-1' if 'my-example-text' already exists

Examples

Basic Usage

// Import and use slugify function
const { slugify } = require('slugify-mongodb');

const slug = slugify('Example Text');
console.log(slug); // Output: 'example-text'

Generating Unique Slugs

const mongoose = require('mongoose');
const { generateUniqueSlug } = require('slugify-mongodb');

const ExampleModel = mongoose.model('Example', new mongoose.Schema({ slug: String }));

async function createUniqueSlug(text) {
  const uniqueSlug = await generateUniqueSlug(text, ExampleModel);
  console.log(uniqueSlug); // Output: 'example-text' or 'example-text-1'
}

createUniqueSlug('Example Text');

See Perfect Example

//create posts in your backend
const Post = require('../model/postModel');
const User = require('../model/userModel');
const Slug = require('slugify-mongodb');

const create = async (req,res)=> {
    const {postedBy, text, title, img, video} = req.body
    try {
        if (!postedBy || !text || !title) {
            res.status(400).json({error: 'posted by, title and text field are required'});
        }
        const user = await User.findById(postedBy);
        if (!user) {
            res.status(400).json({error: 'user not found'});
        }
        if (user._id.toString() !== req.user._id.toString()) {
            res.status(400).json({error: "unauthorized to create steeze post"})
            return;
        }
        const maxLength = 500;
        if (text.length > maxLength) {
            res.status(400).json({error: 'maximum text character is 500'});
        }
        let slug = await Slug.generateUniqueSlug(title,Post);
        const newPost = new Post({
            postedBy,
            title,
            slug,
            text,
            img,
            video
        })
            await newPost.save();
            await User.findByIdAndUpdate(user._id, {$push: {posts: newPost}})
            res.status(201).json(newPost)
    } catch (error) {
        res.status(500).json({error: "unable to create post"})
        console.log(error)
    }
}

##Output

{
  "postedBy": "667edc045fb32d7ffed1a5fe",
  "title": "Todays post",
  "slug": "todays-post-2",
  "text": "testing post 4",
  "img": "image uploaded",
  "video": "video uploaded",
  "likes": [],
  "_id": "6687fffa2a2b81c150749efd",
  "replies": [],
  "createdAt": "2024-07-05T14:15:22.339Z",
  "updatedAt": "2024-07-05T14:15:22.339Z",
  "__v": 0
}

Advance Feature Usage

Without Options

The function will use default values if no options are provided:

const { slugify } = require('slugify-mongodb');

const slug = slugify('My Example Text');
console.log(slug); // Output: 'my-example-text'

With Custom Options

Users can still customize the behavior by providing an options object:

const slug = slugify('My Example Text', {
  separator: '_',
  preserveCase: true,
  maxLength: 15,
});
console.log(slug); // Output: 'My_Example_Text'

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any improvements.

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature-branch).
  3. Make your changes.
  4. Commit your changes (git commit -am 'Add new feature').
  5. Push to the branch (git push origin feature-branch).
  6. Open a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.