之前对这个问题的回答很有帮助,但查看更详细的代码可能会很有用。下面的代码来自我的应用程序的 Express.js 后端。我的应用程序允许用户撰写评论。在查询用户时,我会返回用户所做的所有评论。
user_model.js
import mongoose, { Schema } from 'mongoose';
const UserSchema = new Schema({
firstname: String,
lastname: String,
username: { type: String, unique: true },
reviews: [{ type: Schema.Types.ObjectId, ref: 'Review' }],
}, {
toJSON: {
virtuals: true,
},
});
const UserModel = mongoose.model('User', UserSchema);
export default UserModel;
review_model.js
import mongoose, { Schema } from 'mongoose';
const ReviewSchema = new Schema({
body: String,
username: String,
rating: Number,
}, {
toJSON: {
virtuals: true,
},
});
const ReviewModel = mongoose.model('Review', ReviewSchema);
export default ReviewModel;
review_controller.js
// . . .
export const createReview = (req, res) => {
const review = new Review();
review.username = req.body.username;
review.rating = req.body.rating;
review.body = req.body.body;
review.save()
.then((result) => {
User.findOne({ username: review.username }, (err, user) => {
if (user) {
// The below two lines will add the newly saved review's
// ObjectID to the the User's reviews array field
user.reviews.push(review);
user.save();
res.json({ message: 'Review created!' });
}
});
})
.catch((error) => {
res.status(500).json({ error });
});
};
user_controller.js
export const createUser = (req, res) => {
const user = new User();
user.username = req.body.username;
user.email = req.body.email;
user.save()
.then((result) => {
res.json({ message: 'User created!', result });
})
.catch((error) => {
res.status(500).json({ error });
});
};
// . . .
// returns the user object associated with the username if any
// with the reviews field containing an array of review objects
// consisting of the reviews created by the user
export const getUser = (req, res) => {
User.findOne({ username: req.params.username })
.populate('reviews')
.then((result) => {
res.json(result);
})
.catch((error) => {
res.status(500).json({ error });
});
};