【发布时间】:2013-12-27 03:18:55
【问题描述】:
这是我用来填充相册及其图片的代码:
server.get(url_prefix + '/image', function(req, res, next) {
var album_id = req.query.album_id
Album.findOne(
{_id : album_id}
)
.populate('images')
.exec(function (err, album) {
if (album) {
return res.send({
status: {
error: 0,
message: "Successful"
},
data: {
album: album
}
})
} else
return notify_error(res, "No Results", 1, 404)
})
})
专辑架构:
var AlbumSchema = new Schema(
{
userId:{
type: String,
trim: true
},
albumName:{
type: String,
trim: true
},
albumDescription:{
type: String,
trim: true
},
imageCount:{
type: Number,
default: 0
},
timestamp:{
type: String,
trim: true
},
albumThumbnail:{
type: Object
},
images : [{
type: Schema.Types.ObjectId,
ref: 'Image'
}
]
})
图像架构:
var ImageSchema = new Schema(
{
_album : { type: String, ref: 'Album' },
imageName:{
type: String,
trim: true
},
imageDescription:{
type: String,
trim: true
},
timestamp:{
type: String,
trim: true
},
imageURL:{
type: String,
trim: true
},
imageURLSmall:{
type: String,
trim: true
},
imageThumbnailURL:{
type: String,
trim: true
},
likeCount:{
type: Number,
default: 0
},
commentCount:{
type: Number,
default: 0
},
userLike:{
type: Boolean,
default: false
}
})
我能够填充相册及其图像,在图像架构 imageURL 中仅包含图像名称 (image.jpg),因此在检索时我希望它像 http://localhost/assets/profile/image.jpg 我必须在填充数据或在发送数据之前,因为移动设备使用此 API,因此它们需要完整的路径来显示图像。
那么如何在填充数据的同时向 mongodb 中的字段添加字符串?
提前致谢
【问题讨论】:
-
为什么只在 imageUrl 字段中存储图片的名称?您不能在创建时将图像的完整 url 存储在那里吗?
-
@AlistairNelson:这是个好主意吗?我从一开始就是这样练习的。如果我们需要更改服务器,这将很有帮助。但我猜在任何编程中他们都没有保存图像的完整路径。
-
另一个你可以做你想做的事情的地方是在 .exec(function (err, album) { if (album) { 部分因为这里你有你需要的所有数据,你可以然后在此处操作您的网址,然后再将其发送给客户端
-
@AlistairNelson:感谢您的建议,但问题是,在完成循环之前它发送响应(循环后的代码在循环完成之前执行),所以我需要手动检查循环是否完成后,这变得代码复杂和不专业。所以我正在寻找一些合适的方法。
-
什么循环?如果您在返回响应之前更新您的数据,那么您将能够在响应发送之前做任何您想做的事情。一旦你完成了这项工作,你就可以努力让它以正确的方式做得更好......
标签: node.js mongodb mongoose populate