node.js - 将 objectID 列为选择中的值并保存表单
问题描述
我有 2 个架构,1 个是学校,另一个是老师。这是架构的样子
学校:
var SchoolSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
status: {
type: Number,
default: 1
}
});
module.exports = mongoose.model('School', SchoolSchema);
和老师:
var TeacherSchema = new Schema({
schoolID: {
type: mongoose.Schema.Types.ObjectId, ref: 'School'
},
name: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
});
module.exports = mongoose.model('Teacher', TeacherSchema );
Teacher 中的 SchoolID 是指 School 中一行的 id。使用表单添加教师时,学校显示在选择菜单中,其中值包含学校的id,如下所示:
<b-select id="schoolID" name="schoolID">
<option selected>Select the school</option>
<option v-for="school in schools" v-bind:value="school._id" v-bind:key="school._id">{{ school.name }}</option>
</b-select>
以下是教师注册表格中的完整脚本部分:
<script>
import axios from 'axios'
export default {
name: 'register',
data () {
return {
input: {
name: "",
email: "",
password: "",
schoolID: ""
},
schools: [],
result : "",
errors: []
}
},
created() {
axios.get('http://localhost:8081/public/school/list')
.then(response => {
this.schools = response.data
})
.catch(e => {
this.errors.push(e)
})
},
methods: {
onSubmit (evt) {
evt.preventDefault()
if(this.input.name != "" && this.input.email != "" && this.input.password != "") {
axios.post('http://localhost:8081/api/auth/teacher/register', this.input)
.then(response => {
if (response.data.success == true){
console.log("teacheradded!")
this.result = "teacheraddded!"
}else{
console.log(response.data.msg)
this.errors.push(response.data.msg)
}
})
.catch(e => {
console.log(e.response)
this.errors.push(e)
})
}
}
}
}
</script>
这是教师/注册下的部分代码
router.post('/teacher/register', function(req, res) {
if (!req.body.name || !req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please enter your name, email and password.'});
} else {
var newTeacher = new Teacher({
schoolID: req.body.schoolID,
name: req.body.name,
email: req.body.email,
password: req.body.password
});
// save the teacher
newTeacher .save(function(err) {
if (err) {
console.log(err)
return res.json({success: false, msg: 'Error'});
}
res.json({success: true, msg: 'Successfully created new teacher.'});
});
}
});
但似乎我无法获得在选择中分配为值的学校的 objectID。
解决方案
您必须将b-select
组件绑定到您的input.schoolID
属性,因此您需要添加v-model="input.schoolID"
如下:
<b-select id="schoolID" name="schoolID" v-model="input.schoolID">
<option selected>Select the school</option>
<option v-for="school in schools" v-bind:value="school._id" v-bind:key="school._id">{{ school.name }}</option>
</b-select>
推荐阅读
- r - 在 `dplyr` 的 `mutate()` 中应用函数
- angular - 在页面加载时加载 MDBootstrap 模式
- grails - 带有 SAML 的 Grails 3 - 身份验证失败
- h2 - 在 H2 表名中使用大括号
- image - Xamarin 图像数据在流副本上无效
- sql - SQL Server 中的转换函数
- apache-spark - 如何通过 Spark 将用户定义的元数据添加到 S3 对象
- winapi - Win16 应用程序的清单文件
- sql - 如何将where子句中的值与ID的最大值进行比较?
- java - 编辑:如何发送带有参数和表单数据的帖子请求,如 JAVA 中的邮递员截图?