Mongoose: Schema.ObjectID syntax

Hi, I wrote two models and I want to use the ObjectId to reference the user in the database however it does not work… I don’t know why.

I tried every conceivable syntax …i just bugs.

The ‘ref’ works fine when using a String datatype.

Any ideas on what’s wrong? The rest of my ExerciseTracker program works fine otherwise…

first model:

const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var User = mongoose.Schema({
	user: {
		type: String,
		required: true,
	},

	_id: ObjectId,

});

module.exports = mongoose.model('User', User);

second model:

const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var exercise = mongoose.Schema({
	userId: {
		type: ObjectId,
		ref: 'User'
	},
	description: String,
	duration: Number,
	date: {
		type: Date,
		default: Date.now,
	}
});

module.exports = mongoose.model('Exercise', exercise);

Solved it. There was a conflict with the initialization of the _id: property . If it can help anyone, i ll leave it

1 Like

that looked funny to me, glad you fixed it