I am working to show the rating for every college that is shown to user based on user score. Suppose user A gives college 1 as rating 5, then the rating will be send to mongodb database In database I have made a collection named rating
ratingSchema = mongoose.Schema({
rating: Number,
userId: {
ref: 'users',
type: mongoose.SchemaTypes.ObjectId
// a string or whatever your id is
},
collegeId: {
ref: 'colleges',
type: mongoose.SchemaTypes.ObjectId
},
})
const Rating = mongoose.model('rating', ratingSchema);
The query written in nodeJS file is:
Rating
.findOne({})
.populate('userId')
.populate('collegeId');
How to post the rating from react to mongodb.
the function made in react is : component/Report.js
const StarRating = (props) => {
console.log(props);
return (
<div>
{Array(5)
.fill(0)
.map((_, idx) => (
<label key={idx}>
<input
type="radio"
name="rating"
onChange={handleRate}
value={props.ratingValue}
checked={idx === props.ratingValue}
/>
<FaStar color={idx < 3 ? "#01af93" : "#bbb"} />
</label>
))}
</div>
);
};
const Report = (props) => {
const { advices } = useSelector((state) => state.advice);
const [rate, setRating] = useState(null);
useEffect(() => {
if (!advices) {
dispatch(fetchAdvices(history));
}
});
useEffect(() => {
async function fetchRate() {
try {
const { rating } = await api.get(paths.FETCH_RATING);
console.log(rating "user rating");
} catch(error) {
console.log(error);
}
};
fetchRate();
}, []);
const handleRate = async() => {
const rate = await api.post(paths.UPDATE_RATING, {rating:rate});
props.setRating(rate)
}
return (
<>
<Container>
<Grid>
<Fragment>
<Grid >
<Card>
<CardContent><> <div>
<StarRating setRating={(val) => setRate(val)} ratingValue={rate} />
</div></></CardContent>
</Card>
</Grid>
</>
)};
i want to set rating for college and next time when user sees the order of colleges will be in the highest ranking to lowest ranking.
CodePudding user response:
const router = express.Router();
router.post('/ratings', async (req, res) => {
const { rating, collegeId } = req.body;
// just an example to userId, depends on your authentication method
const userId = req.user.id
// example validation
if (!rating || !collegeId) {
return res.status(400).send({ message: 'bad request.' });
}
try {
const newRating = new Rating({rating, collegeId, userId})
await newRating.save()
return res.status(201).json({message:"success", rating:newRating})
} catch (error) {
res.status(500).send({ message: 'database error' });
}
});
then you can axios.post("yourApiUrl/ratings", {rating: 5, collegeId:123456})
router.get('/ratings', async (req, res) => {
try {
// maybe you need modify I didn't memorize mongoose methods
const ratings = await Rating.find({userId}
.populate('userId')
.populate('collegeId').sort({rating:1});
return res.status(201).json({message:"success", ratings})
} catch (error) {
res.status(500).send({ message: 'database error' });
}
});
this route gives ordered by user ratings.