如何在mongoose中通过slug属性值而不是id查询特定的Post?

6pp0gazn  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(88)

我知道如何通过ID查询特定的帖子。然而,我想使用slug属性的职位,而不是它的id来查询它。我该怎么做?

//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')

下面是Post模型:

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)
ztmd8pv5

ztmd8pv51#

如果有多个文档共享相同的slug,则可以使用find();如果slug对于每个文档都是唯一的,则可以使用findOne()

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

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

//这个可以用

相关问题