我知道如何通过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)
1条答案
按热度按时间ztmd8pv51#
如果有多个文档共享相同的
slug
,则可以使用find()
;如果slug
对于每个文档都是唯一的,则可以使用findOne()
或
//这个可以用