猫鼬原型:如何动态插入URL?
我尝试为猫鼬模式创建原型. 数据库包含一行,其中包含图片列表.
I try to create a prototype for a mongoose schema. The database contains a row with a list of pictures.
示例:
{
"_id": ObjectId("55814a9799677ba44e7826d1"),
"album": "album1",
"pictures": [
"1434536659272.jpg",
"1434536656464.jpg",
"1434535467767.jpg"
],
"__v": 0
}
知道如何使用示例原型为每张图片注入URL,以及之后如何才能以JSOn格式(用于API)从集合中获取所有数据(带有图片和url),将是非常棒的.
It will be awesome to know how i can inject an URL for each pictures with for example a prototype and how after i can get all the datas from the collection (with pictures and url) in JSOn format (for an API).
我测试了许多不同的方法,但是没有用.
I tested many different approach but it doesn't work.
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存储在数据库中)?
How I can inject "virtually" the URL for each pictures (I don't want to store the url in the DB) ?
以下是使用一个实例的示例方法:
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响应),请使用虚拟" 代替:
If you want the URL's to be part of the document object (for instance, to use as JSON response), use a "virtual" instead:
...
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 }) );