如何转换多个Mongoose文档?

我的每个模式都有一个方法,称为toItem() ,它将文档转换为更加冗长/可读的forms。 我如何创build一个toItems()方法来为文档数组做同样的事情?

我的示例架构:

 var mongoose = require('mongoose'); var membershipSchema = new mongoose.Schema({ m : { type: mongoose.Schema.ObjectId, ref: 'member' }, b : { type: Date, required: true }, e : { type: Date }, a : { type: Boolean, required: true } }); var accountSchema = new mongoose.Schema({ n : { type: String, trim: true }, m : [ membershipSchema ] }); accountSchema.methods.toItem = function (callback) { var item = { id : this._id.toString(), name : this.n, members : [] }; (this.m || []).forEach(function(obj){ item.members.push({ id : obj.m.toString(), dateBegin : obj.b, dateEnd : obj.e, isAdmin : obj.a }); }); return callback(null, item); }; var accountModel = mongoose.model('account', accountSchema); module.exports = accountModel; 

我试过使用静态,方法和第三方库,但没有干净的作品。 我想保持这个尽可能简单/干净,并有我的模型文件中包含toItems()函数。

先谢谢你。

toItem()方法是特定于模式/模型的。 你的toItems()方法听起来更像是一个实用的方法,它可以被所有的模型使用。 如果是这样,我会移动在实用程序文件中创buildtoItems()方法。 您只需传入文档数组,实用程序方法就会在每个文档上调用单独的toItem()方法。

例如:

 var async = require('async'); var toItems = function (models, callback) { models = models || []; if (models.length < 1) { return callback(); } var count = -1, items = [], errors = []; async.forEach(models, function (model, next) { count++; model.toItem(function (err, item) { if (err) { errors.push(new Error('Error on item #' + count + ': ' + err.message)); } else { items.push(item); } next(); }); }, function (err) { if (err) { return callback(err); } if (errors.length > 0) { return callback(errors[0]); } return callback(null, items); }); }; module.exports.toItems = toItems;