Thursday, 25 May 2017

Page is displayed before async call finished? Output undefined. Mongoose.js

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:

enter image description here

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: {} })

Have spent two hours on this issue with no luck! Any help is appreciated. Only thing I can think of is that the view renders before the call is completed and therefore shows undefined.. if that is the case, how can I fix that?



via Govind Rai

No comments:

Post a Comment