node.js/mongoDB: Return custom value if field is null -
what want query database documents and, if field not set, homecoming custom value instead of it.
imagine i'm having collection of songs
, of these have field pathtocover
set , don't. these, want homecoming url placeholder image store in config variable.
i running node.js , mongodb express , mongoose.
i not sure best approach is. obvious solution query documents , in callback iterate on them check if field set. feels quite superfluous.
currently, code looks this:
exports.getbyalbum = function listbyalbum(query, callback) { song.aggregate({ $group: { _id: '$album', artists: { $addtoset: '$artist' }, songs: { $push: '$title' }, covers: { $addtoset: '$pathtocover'}, genres: { $addtoset: '$genre'}, pathtocover: { $first: '$pathtocover'} } }, function (err, result) { if (err) homecoming handleerror(err); result.foreach(function(album) { if ( album.pathtocover == null) { album.pathtocover = config.library.placeholders.get('album'); } }) callback(result); }); }
what best approach this?
thanks lot in advance!
where value of field either null
or unset , perchance missing document, utilize $ifnull
in aggregation set alternate value:
exports.getbyalbum = function listbyalbum(query, callback) { var defaultcover = config.library.placeholders.get('album'); song.aggregate( [ { "$group": { "_id": "$album", "artists": { "$addtoset": "$artist" }, "songs": { "$push": "$title" }, "covers": { "$addtoset": { "$ifnull": [ "$pathtocover", defaultcover ] } }, "genres": { "$addtoset": "$genre" }, "pathtocover": { "$first": { "$ifnull": [ "$pathtocover", defaultcover ] } } }} ], function (err, result) { if (err) homecoming handleerror(err); callback(result); } ); }
if empty string utilize $cond
statement $eq
test in place of $ifnull
:
{ "$cond": [ { "$eq": [ "$pathtocover", "" ] }, defaultcover, "$pathtocover" ] }
either statement can used within of grouping operator replace value considered.
if worried perhaps not "all" of values set on song, utilize $min
or $max
appropriate info pick 1 of values instead of using $first
.
node.js mongodb mongoose mongodb-query aggregation-framework
No comments:
Post a Comment