mongoose原型:如何dynamic地插入一个url?

我尝试创build一个mongoose模式的原型。 该数据库包含一个包含图片列表的行。

例如:

{ "_id": ObjectId("55814a9799677ba44e7826d1"), "album": "album1", "pictures": [ "1434536659272.jpg", "1434536656464.jpg", "1434535467767.jpg" ], "__v": 0 } 

知道如何为每个图片注入一个URL(例如原型),以及如何从JSOn格式(用于API)的集合(包括图片和url)获取所有数据之后,这将是非常棒的。

我testing了许多不同的方法,但不起作用。

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PicturesSchema = new Schema({ album: { type: String, required: true, trim: true }, pictures: { type: Array, required: false, trim: true } }); var Pictures = mongoose.model('Pictures', PicturesSchema); // Not working Pictures.prototype.getPics = function(){ return 'https://s3.amazonaws.com/xxxxx/'+ this.pictures; } module.exports = Pictures; 

我怎样才能注入“虚拟”每个图片的url(我不想将url存储在数据库中)?

以下是使用实例方法的示例:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PicturesSchema = new Schema({ album : { type : String, required : true, trim : true }, pictures : { type : Array, required : false, trim : true } }); // Make sure this is declared before declaring the model itself. PicturesSchema.methods.getPics = function() { // `this` is the document; because `this.pictures` is an array, // we use Array.prototype.map() to map each picture to an URL. return this.pictures.map(function(picture) { return 'https://s3.amazonaws.com/xxxxx/'+ picture; }); }; var Pictures = mongoose.model('Pictures', PicturesSchema); // Demo: var pictures = new Pictures({ album : 'album1', pictures : [ '1434536659272.jpg', '1434536656464.jpg', '1434535467767.jpg' ] }); console.log( pictures.getPics() ); 

如果您希望URL是文档对象的一部分(例如,用作JSON响应),请使用“虚拟” :

 ... PicturesSchema.virtual('pictureUrls').get(function() { return this.pictures.map(function(picture) { return 'https://s3.amazonaws.com/xxxxx/'+ picture; }); }); ... // Demo: console.log('%j', pictures.toJSON({ virtuals : true }) );