提问人:Moses Ndirangu 提问时间:11/9/2023 最后编辑:Moses Ndirangu 更新时间:11/9/2023 访问量:20
在MongoDB中的架构和查询之间创建引用,以从相同的模式中获取数据
Creating references between schemas in MongoDB and queries to get the data from the same
问:
以下是我正在使用的两个架构: UserSchema
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
{
_id: {
type: Schema.Types.ObjectId,
},
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
// match: /.+\@.+\..+/,
unique: true,
},
phoneNumber: {
type: String,
unique: true,
},
image: {
type: String,
},
password: {
type: String,
unique: true,
required: true,
},
tokens: [{ type: Object }],
code: String,
accountType: {
type: String,
},
isAdmin: {
type: Boolean,
default: false,
},
location: {
type: String,
},
coords: { type: Object },
isEditor: {
type: Boolean,
default: false,
},
isVerified: {
type: Boolean,
default: false,
},
isSuspended: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
export default mongoose.model("User", UserSchema);
评论架构
import mongoose from "mongoose";
const ReviewsSchema = new mongoose.Schema(
{
writer: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
body: {
type: String,
required: true,
},
rating: {
type: Number,
required: true,
},
},
{ timestamps: true }
);
export default mongoose.model("Reviews", ReviewsSchema);
如何创建控制器函数来获取与特定用户关联的评论?
以下是我用来获取单个评论的控制器函数:reviewController,.js
export const getReview = async (req, res, next) => {
try {
const review = await Reviews.findById(req.params.id);
res.status(200).json({ success: true, review });
} catch (err) {
next(err);
}
};
当我使用 Postman 测试 api 端点时,以下是我得到的结果:
{
"success": true,
"review": {
"_id": "654c2568df670257734ee11c",
"body": "MechLocator has helped me big time",
"rating": 0.95,
"createdAt": "2023-11-09T00:18:48.080Z",
"updatedAt": "2023-11-09T00:18:48.080Z",
"__v": 0
}
}
如您所见,我没有从对服务器的调用中填充 writer 字段。我希望看到此字段填充了与此评论关联的用户的 ObjectId。
我做错了什么?
答: 暂无答案
上一个:猫鼬静态变量/全局非易失性变量
下一个:合并来自多个数据库的表
评论