Search code examples
node.jsmongodbexpressmongoose

How do I query a specific Post by slug property value in mongoose instead of id?


I know how to query a specific post by id. However I want to use the slug property of the post instead of its id to to query it. How do I do so ?

//Instead of req.params.id, we have req.params.slug instead
//How do get the post in this case if the Post database model has a slug property.  
//We have the req.params.slug

//This is what needs to be changed
const post = await Post.findById(req.params.id, (error, post) => {
    console.log(error, post)
  }).populate('author')

Here is the Post model:

const mongoose = require('mongoose')

const PostSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },

  subtitle: {
      type: String,
      required: true,
  },
  author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
  },

  content: {
      type: String,
      required: true
  },
  image: String,
  category: String,
  subCategory: String,
  createdAt: {
      type: Date,
      default: new Date() 
  }
})
module.exports = mongoose.model('Post', PostSchema)

Solution

  • you can use find() if you have many documents share the same slug or findOne() if this slug is unique for each document

    Post.find({ slug: req.params.slug }, (error, post) => {
        console.log(error, post)
    });
    

    or

    Post.findOne({ slug: req.params.slug }, (error, post) => {
        console.log(error, post)
    });
    

    //This one does work