如何查询猫鼬而不是ID的特定的“按子项发布"属性值? [英] How do I query a specific Post by slug property value in mongoose instead of id?

查看:91
本文介绍了如何查询猫鼬而不是ID的特定的“按子项发布"属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何通过ID查询特定帖子.但是我想使用帖子的slug属性而不是它的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')

这里是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(). >

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

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

这篇关于如何查询猫鼬而不是ID的特定的“按子项发布"属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆