Home > Blockchain >  Mongoose adding url slug to the returned JSON object
Mongoose adding url slug to the returned JSON object

Time:02-18

Sorry in advance if my formatting is off! I'm building a project using MongoDB, Mongoose, and Express. Right now I'm trying to use Mongoose to read a document from the MongoDB database. For some reason it's prepending the word "slug" to the document I'm fetching from the database. The result I'm getting is this: [{"slug":"","title":"test","id":"62002ba44b05edb74c1a9cd8"}]

When the result I should be getting is this: [{"title":"test","id":"62002ba44b05edb74c1a9cd8"}]

I'm thinking there's an unexpected side effect from one of the libraries I'm using but I can't figure out what's causing it. It's like this before I call res.render("Test", testRes) so it might even be coming from the database like this somehow? I've been stumped on this for hours now.

const express = require('express');

const router = express.Router();

const mongoose = require('mongoose');

const Test = mongoose.model('Test');


const sanitize = require('mongo-sanitize');

router.get('/test/:testSlug', async function(req, res) {
    const testSlug = req.params.testSlug;

    const testSearchParam = {
        slug: sanitize(testSlug)
    };

    console.log("search param", testSearchParam.slug);

    const testRes = await Test.find(
        {
            title: testSearchParam.slug
        }
    );
    
    res.render("Test", testRes);
});
  
module.exports = router;


and here is my schema for the Test data format:



const mongoose = require('mongoose');

const URLSlugs = require('mongoose-url-slugs');

const { toJSON } = require('../plugins');


const TestSchema = new mongoose.Schema({

  title: {
    type: String,
    required: true
  }},
  {
    collection: 'test'
  }
);

TestSchema.plugin(URLSlugs('title'));

TestSchema.plugin(toJSON);


/**
 * @typedef Test
 */

const Test = mongoose.model('Test', TestSchema);

module.exports = Test;

CodePudding user response:

Since you are using mongoose-url-slugs, the package has a default option to create a slug field in mongoose schema.

addField (Default: True) - Add slug field to mongoose schema.

See here: https://www.npmjs.com/package/mongoose-url-slugs#options-and-defaults

  • Related