【发布时间】:2020-12-28 15:52:30
【问题描述】:
这是我的 CRUD 代码,现在我想使用动态值执行搜索。
const express = require('express')
const router = express.Router()
const cors = require('cors')
//Importing Jobs Model
const JobsModel = require('../../models/jobs')
//POST Req
router.post('/', async (req,res) => {
const newJobPost = new JobsModel(req.body)
try{
const jobPost = await newJobPost.save()
if(!jobPost) throw Error('Error, JobPost Not Saved...!')
res.status(200).json(jobPost)
}catch(err){
res.status(400).json({msg:err})
}
})
//GET All Req
router.get('/',cors(), async (req,res) => {
try{
const getJobs = await JobsModel.find()
if(!getJobs) throw Error('Error, No Jobs Found...!')
res.status(200).json(getJobs)
}catch(err){
res.status(400).json({msg:err})
}
})
//GET Single Req
router.get('/:id',cors(), async (req,res) => {
try{
const getJob = await JobsModel.findById(req.params.id)
if(!getJob) throw Error('Error, Job Not Found...!')
res.status(200).json(getJob)
}catch(err){
res.status(400).json({msg:err})
}
})
//DELETE Req
router.delete('/:id',cors(), async (req,res) => {
try{
const delJobs = await JobsModel.findByIdAndDelete(req.params.id)
if(!delJobs) throw Error('No Jobs Found to Delete...!')
res.status(200).json({success: true})
}catch(err){
res.status(400).json({msg:err})
}
})
//UPDATE Req
router.patch('/:id',cors(), async (req,res) => {
try{
const updateJob = await JobsModel.findByIdAndUpdate(req.params.id, req.body)
if(!updateJob) throw Error('Error, No Jobs Found to Update...!')
res.status(200).json({success: true})
}catch(err){
res.status(400).json({msg:err})
}
})
//SEARCH Req
module.exports = router
请那里的任何人帮助我执行搜索查询。我也在谷歌上做了很多研究,以找到“从 mongodb get req 搜索特定数据”的解决方案.......................... ..................................................... .......
【问题讨论】:
-
请指定您要搜索的内容、所需的结果并提供您的数据库或模型的示例结构
-
const mongoose = require('mongoose') const Schema = mongoose.Schema const JobSchema = new Schema({ title:{ type: String, required: true }, category:{ type: String, required: true }, company:{ type: String, required: true }, city:{ type: String, required: true }, description:{ type: String, required: true } }) module.exports = mongoose.model('Jobs',JobSchema)这是包含所有 mongodb 字段的模型文件 -
您要搜索什么?按标题、城市或什么?
-
我要按标题、类别和城市搜索
-
我真的被困在这请帮助@Qudusayo
标签: javascript node.js mongodb express rest