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;
});
}
via Azuli42
No comments:
Post a Comment