我目前正在使用RESTful API,并且正在尝试参考课程文档中的用户模式,这样,当POST请求发送到课程路线时,将在数据库中创建课程并具有作为其字段之一,是对创建它的用户的引用。但是,对于我一生来说,我无法弄清楚为什么我发布时没有显示“用户”字段。在Stack上似乎有很多这样的问题,所以我可能只是增加了一些,但我尝试了他们的解决方案,但它们对我没有用
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
emailAddress: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
var CourseSchema = new Schema({
user: {type: Schema.Types.ObjectId, ref: 'User'}, //FOR some reason this is not showing up on any courses created using the
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
estimatedTime: {
type: String
},
materialsNeeded: {
type: String
}
});
var User = mongoose.model('User', userSchema);
var Course = mongoose.model('Course', CourseSchema);
module.exports = {Course, User};
您在这里看到的任何东西都可以阻止创建新课程时出现用户字段吗?
我附上了一些截图以进一步说明。
该第一张图片是当前已认证用户凭证的屏幕(显然是假数据)。这是正在发送新课程的POST请求的用户。我希望他的信息会附在课程中(请参见屏幕快照3)
此图像显示了发送的请求的主体。您可以看到键值对与CourseSchema中的键值对匹配。我希望发送POST请求后将创建“用户”字段。
谢谢大家来看看!
答案 0 :(得分:0)
用户字段不会自动添加到课程文档中。您必须在请求正文中或创建课程时手动设置用户字段。 要发送的课程正文示例:-
{
user: "userId",
title: "test",
description: "test",
estimatedTime: "test",
materialsNeeded: 1
}
此外,此结果将不包含您在预期结果中提到的整个用户文档。它只会返回userId。但是,在访问课程时,您可以填充用户字段以获取整个用户文档。相同的例子
Course.find({...query}).populate("user")