gpt4 book ai didi

node.js - Mongoose 原型(prototype): how to insert an url dynamically?

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:00 24 4
gpt4 key购买 nike

我尝试为 Mongoose 模式创建一个原型(prototype)。数据库包含一行图片列表。

示例:

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

如果知道如何为每张图片注入(inject)一个 URL(例如原型(prototype)),以及如何以 JSOn 格式(用于 API)从集合中获取所有数据(包含图片和 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 }
});

var Pictures = mongoose.model('Pictures', PicturesSchema);

// Not working
Pictures.prototype.getPics = function(){
return 'https://s3.amazonaws.com/xxxxx/'+ this.pictures;
}

module.exports = Pictures;

如何“虚拟”注入(inject)每张图片的 URL(我不想将 URL 存储在数据库中)?

最佳答案

这是一个使用 an instance method 的示例:

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 响应),请使用 "virtual"相反:

...
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 }) );

关于node.js - Mongoose 原型(prototype): how to insert an url dynamically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30889833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com