我创建了一个Mongoose模式,并将studentId
字段类型添加为studentId: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'},
,目的是填充该集合。
填充部分已经完成,工作正常。但是,当我创建一个新文档(在studentClass中(时——因此,我必须将studentId
字段作为String
发送——我必须尝试将String
转换为ObjectId
,如下所示,
const studentObjectId = mongoose.Schema.Types.ObjectId(studentId);
使用上面的方法对我不起作用。而且,它没有触发任何错误。它似乎没有编译那一行之后的代码。
我还导入了Mongoose作为const mongoose = require('mongoose');
studentClass
模型如下,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const studentClassModel = new Schema({
studentId: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'},
groupId: {type: String}
});
module.exports = mongoose.model('StudentClass', studentClassModel, 'STUDENT_CLASS')
mongoose.Schema.Types
用于声明模式。
CCD_ 10用于构造这些类型。
使用
const studentObjectId = mongoose.Types.ObjectId(studentId);