我该如何实现
[{
"title": "pranam",
"year": "2016",
"rating": 9,
"actors": [
{
"name": "Amir",
"birthday": "16 Aug 1982",
"country": "Bangladesh"
},
{
"name": "Imran",
"birthday": "15 Aug 1982",
"country": "Bangladesh"
}
]
}]
我已经尝试过了……
models / actors.js
const Joi = require('joi');
const mongoose = require('mongoose');
const actorSchema = new mongoose.Schema({
name:{
type: String,
required: true,
min: 5,
max:50
},
birthday:{
type: String,
required: true
},
country:{
type: String,
required: true
}
});
models / movies.js
const mongoose = require('mongoose');
const Joi = require('joi');
const actorSchema = require('../models/actors');
const movieSchema = new mongoose.Schema({
title:{
type:String,
required:true,
min: 5,
max: 50
},
year:{
type: String,
required: true,
min:2,
max:4
},
rating:{
type: Number,
required: true,
min:0,
max:10
},
actors: {
type: actorSchema,
required: true
}
});
routes / movies.js
const { Movie, validate} = require('../models/movies');
const { Actor} = require('../models/actors');
const auth = require('../middleware/auth');
const router = express.Router();
router.get('/', auth, async(req, res)=>{
const movies = await Movie
.find({}, { _id:0, __v:0 })
res.send(movies);
});
router.post('/', async(req, res)=>{
const {error} = validate(req.body);
if(error) return res.status(400).send(error.details[0].message)
//May be problem is hare, But I can not solve
const actor = await Actor.findById(req.body.actorId);
if(!actor) return res.status(400).send('Invalid Actors');
let movie = new Movie({
title: req.body.title,
year: req.body.year,
rating: req.body.rating,
actors:[{
name: actor.name,
birthday: actor.birthday,
country: actor.country
}]
});
try {
movie = await movie.save();
res.send(movie)
} catch (ex) {
console.log("Invalid Movie ");
}
});
module.exports =router;
我用邮递员的POST方法输入 {“标题”:“我讨厌爱情故事”,“评分”:“ 9”,“ actorId”:[“ 5d99ac95f17917117068631b”,“ 5d99ad75c4edd61f98af740b”] } 这仅显示通过GET api调用输出的电影中的第一个演员数据, 如何在电影中显示更多演员数据。
答案 0 :(得分:0)
在问题的上下文中,其他一切看起来都很好,直到在route / movies.js中达到这一点为止:
const actor = await Actor.findById(req.body.actorId);
我认为查询不正确,首先,Model.findById()仅接受一个ID,而不接受ID数组。其次,您要在此处执行的操作是获取由actorId数组中的ID标识的所有参与者,这是一个有效的查询:
const actors = await Actor.find(
// Filter: fetch all actors whose Id is in the array of ids provided in the request
{ _id: { $in: req.body.actorId } },
// Projection: Include just the name, birthday and country in the response, if any.
{ name: 1, birthday: 1, country: 1 }
);
您可以检查Model.find()以获得有关如何使用其查询界面的更多信息。
在那里的查询应该返回多个参与者,这就是您所需要的,然后,您可以使用该实例化一个新的电影模型:
new Movie({
title: req.body.title,
year: req.body.year,
rating: req.body.rating,
actors,
});