如何在mongoose中查询特定的Post-by-slug属性值而不是id



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

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

如果有多个文档共享同一个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)
});

//这个确实有效

最新更新