如何使用javascript从MongoDB获取一个ID为URL的文档
我正在制作一个基本的电影应用程序项目,我的电影模式如下所示:如何使用javascript从MongoDB获取一个ID为URL的文档,javascript,mongodb,express,mongoose,Javascript,Mongodb,Express,Mongoose,我正在制作一个基本的电影应用程序项目,我的电影模式如下所示: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: true, lowercase: true, trim: true, e
const movieSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
genre: {
type: String,
required: true,
lowercase: true,
trim: true,
enum: ['comedy', 'horor', 'romantic', 'action']
}
});
const Movie = mongoose.model('Movie', movieSchema);
async function getMovie(id) {;
return await Movie
.findById(id)
.select('name genre')
}
router.get("/:id", async(req, res) => {
try{
const movie = await getMovie(req.params.id);
console.log(movie);
res.send(movie);
}
catch(err){
console.log("Error", err)
}
});
我试着用身份证拍一部电影,但这样不行
async function getMovie(id) {;
return await Movie
.find({"_id": {id}})
.select('name genre')
}
router.get("/:id", async(req, res) => {
try{
const movie = await getMovie(req.params.id);
if (!movie) return res.status(404).send("The genre with the given ID does not exist.");
console.log(movie);
res.send(movie);
}
catch(err){
console.log("Error", err)
}
});
我有两个错误:
顺便说一句,使用postman检查请求我应该在getMovie()函数中使用findById方法,如下所示:
const movieSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
genre: {
type: String,
required: true,
lowercase: true,
trim: true,
enum: ['comedy', 'horor', 'romantic', 'action']
}
});
const Movie = mongoose.model('Movie', movieSchema);
async function getMovie(id) {;
return await Movie
.findById(id)
.select('name genre')
}
router.get("/:id", async(req, res) => {
try{
const movie = await getMovie(req.params.id);
console.log(movie);
res.send(movie);
}
catch(err){
console.log("Error", err)
}
});
您发送的请求如何?