Remi M
Remi M

Reputation: 436

Mongoose - Query exec() never resolves in model method

In an attempt to refactor some code that will be used in different places, I moved this method which was already working from a controller to a Mongoose model.

In the model, the trackQuery.exec() never reaches the callback, never resolves. If I resolve without the exec() or without waiting for the exec(), it works fine. The trackQuery is filled properly with a Mongoose Query.

What is the subtlety about Mongoose models that I don't get ?

ArtistSchema.methods.insertRelatedTracks = function (items) {
    const newTracksToSave = items.map((item) => {
        return new Promise((resolve, reject) => {
            const TrackModel = mongoose.model('Track'),
                trackQuery = TrackModel.findOne({ externalID: item.id })
            ;

            return trackQuery.exec((err, track) => {
                if (err) { 
                    return reject(err);
                }

                if (!track) {
                    let track = new TrackModel({
                        externalID: item.id,
                        provider: item.provider,
                        title: item.title,
                        artist: item.artist,
                        artistID: this._id,
                        artistExternalID: this.externalID,
                        thumbnail: item.thumbnail,
                        publishedAt: item.publishedAt,
                        count: 0
                    });

                    return track.save((err, res) => {
                        if (err) {
                            return reject(err);
                        }

                        return resolve(res);
                    });
                }

                return resolve(track);
            });
        });
    });

    return Promise.all(newTracksToSave).then(() => {
        return this;
    }).catch((err) => {
        console.error(err);
        return this;
    });
}

Upvotes: 0

Views: 634

Answers (1)

Remi M
Remi M

Reputation: 436

The solution for me was to manually import the TrackModel instead of relying on the usual runtime mongoose.model('Track') method. I have no explications why mongoose.model doesn't work in this case. Any hints are welcomed.

Upvotes: 1

Related Questions