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

瘦欲@ 提交于 2020-04-17 22:53:14

问题


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)

回答1:


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)
});


来源:https://stackoverflow.com/questions/61165001/how-do-i-query-a-specific-post-by-slug-property-value-in-mongoose-instead-of-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!