Tharindu Lakshan
Tharindu Lakshan

Reputation: 6116

Creating new ObjectId using ``mongoose.Schema.Types.ObjectId`` is not working

I have created a Mongoose schema and added the studentId field type as studentId: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'},, the purpose of populating that collection.

The populating part was done and it's working fine. But when I create a new document (in studentClass)—I have send studentId field as a String because of that—I have to try to convert String to ObjectId as follows,

const studentObjectId = mongoose.Schema.Types.ObjectId(studentId);

Using the above method was not working for me. Also, it did not trigger any errors. It seems like it is not compiling the code after that line.

I have also imported Mongoose as const mongoose = require('mongoose');

studentClass model as follows,

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')

Upvotes: 3

Views: 5845

Answers (1)

Joe
Joe

Reputation: 28326

mongoose.Schema.Types are for declaring schema.

mongoose.Types are for constructing those types.

Use

const studentObjectId = mongoose.Types.ObjectId(studentId);

Upvotes: 5

Related Questions