My activity model has a property which is a reference to an ObjectId in the units table. The method works fine, in my opinion, as console logging unit.name
logs correct name and also never hits the catch clause so there is no error in retrieval of the name, so I assume that it is being returned as well.
Unfortunately, assuming activity
is an instance of activities, calling activity.unit_id
in my view returns undefined and my view shows undefined. All other properties are being printed properly:
My activity model's schema:
var activitySchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
pointsPerUnit: {
type: Number,
required: true
},
unit_id: {
type: Schema.Types.ObjectId,
ref: 'Unit',
get: function(unit_id) {
Unit.findById(unit_id).then((unit) => {
console.log(unit.name)
return unit.name
}).catch((e) => console.log(e));
}
}
});
Here is what I am calling in my .pug
file:
h2 All Activities
each activity in activities
p= "Name: " + activity.name
p= "Description: " + activity.description
p= "Points Per Unit of Excersise: " + activity.pointsPerUnit
p= "Unit: " + activity.unit_id
hr
I am also explicity logging mongoose
queries to my console. Here's the execution from mongoose
, which is also correct:
Mongoose: units.findOne({ _id: ObjectId("592679205a7b0e0c8fe7f47f") }, { fields: {} })
Mongoose: units.findOne({ _id: ObjectId("592679205a7b0e0c8fe7f47f") }, { fields: {} })
Here is the controller code for the route:
/* GET users listing. */
router.get('/new', function(req, res, next) {
Activity.find({}).then((activities) => {
res.render('activities/new', {activities});
});
});
Have spent two hours on this issue with no luck! Any help is appreciated.