【发布时间】:2016-06-22 17:42:15
【问题描述】:
我正在使用 Mongoose、Express 和 GridFS-Stream 为我的应用程序编写 API。我有一个用户将创建的文章的架构:
var articleSchema = mongoose.Schema({
title:String,
author:String,
type: String,
images: {type: Schema.Types.ObjectId, ref: "fs.files"},
datePublished: { type: Date, default: Date.now },
content: String
})
var Article = mongoose.model("article", articleSchema, "articles");
当用户上传图片时,我的 grid-fs 设置:
api.post('/file', fileUpload.single("image"), function(req, res) {
var path = req.file.path;
var gridWriteStream = gfs.createWriteStream(path)
.on('close',function(){
//remove file on close of mongo connection
setTimeout(function(){
fs.unlink(req.file.path);
},1000);
})
var readStream = fs.createReadStream(path)
.on('end',function(){
res.status(200).json({"id":readStream.id});
console.log(readStream);
})
.on('error',function(){
res.status(500).send("Something went wrong. :(");
})
.pipe(gridWriteStream)
});
现在它设置为当用户选择图像时,它会自动通过 gridfs-stream 上传它,将它放在一个临时文件夹中,然后在它上传到 mongo 服务器时将其删除,并在控制台中返回什么ObjectId 是。好了,find 和 dandy 就这些了,但是我们需要将这个 ID 与 articleSchema 关联起来,所以当我们在应用程序中调用该文章时,它会显示关联的图像。
关于我们在用户点击提交时创建/更新文章:
createArticle(event) {
event.preventDefault();
var article = {
type: this.refs.type.getValue(),
author: this.refs.author.getValue(),
title: this.refs.title.getValue(),
content: this.refs.pm.getContent('html')
};
var image = {
images: this.refs.imageUpload.state.imageString
};
var id = {_id: this.refs.id.getValue()};
var payload = _.merge(id, article, image);
var newPayload = _.merge(article, image)
if(this.props.params.id){
superagent.put("http://"+this.context.config.API_SERVER+"/api/v1.0/article/").send(payload).end((err, res) => {
err ? console.log(err) : console.log(res);
});
} else {
superagent.post("http://"+this.context.config.API_SERVER+"/api/v1.0/article").send(newPayload).end((err, res) => {
err ? console.log(err) : console.log(res);
this.replaceState(this.getInitialState())
this.refs.articleForm.reset();
});
}
},
所以我需要它做的是,当用户在创建文章时点击提交时,调用我刚刚上传到架构的图像部分的图像的 ID。我已经尝试在提交时进行读取流,但同样,问题是我无法获取 ID 或文件名来关联它。
它们被存储在 mongo 数据库中,它创建 fs.files 和 fs.chunks,但对于我来说,我无法弄清楚如何获取这些数据并将其附加到架构,甚至只是获取在不知道 ObjectId 的情况下取出数据。
那么如何从 fs.files 或 fs.chunks 中调用 objectid 以将其附加到架构中?在架构中如何引用 fs.files 或块?所以它知道objectid与什么相关联?
我可以提供更多数据,如果我所拥有的数据含糊不清,我就有这样做的坏习惯。对不起。
【问题讨论】:
标签: javascript mongodb express mongoose gridfs-stream