From 28ae1e8ee65689201cc910af0d44c0924ca62b13 Mon Sep 17 00:00:00 2001 From: Maik Marschner Date: Fri, 6 May 2016 19:56:57 +0200 Subject: [PATCH] Add a function to update a file's metadata. --- lib/index.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/lib/index.js b/lib/index.js index a892c55..fe8466a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -144,6 +144,41 @@ Grid.prototype.findOne = function (options, callback) { }); } +/** + * Update the metadata of the file matched by passing any options, at least an _id or filename + * + * @param {Object} options + * @param {Object} metadata + * @param {Function} callback + */ + +Grid.prototype.updateMetadata = function (options, metadata, callback) { + if ('function' != typeof callback) { + throw new Error('updateMetadata requires a callback function'); + } + var find = {}; + for (var n in options) { + if (n != 'root') { + find[n] = options[n]; + } + } + if (find._id) { + find._id = this.tryParseObjectId(find._id) || find._id; + } + var collection = options.root && options.root != this.curCol ? this.db.collection(options.root + ".files") : this.files; + if (!collection) { + return callback(new Error('No collection specified')); + } + var newMetadata = {} + for (var m in metadata) { + newMetadata['metadata.' + m] = metadata[m] + } + collection.update(find, { $set: newMetadata }, function(err) { + if (err) { return callback(err); } + callback(null); + }); +} + /** * Attemps to parse `string` into an ObjectId *