我有2个模式,一个是学校,另一个是老师。这是架构的样子
学校:
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 );
教师中的SchoolID是指学校中一行的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.'});
});
}
});
但似乎我无法获得分配给select中的值的school的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>
关于node.js - 在选择和保存表单中列出objectID作为值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52560663/