我正在使用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是什么。好了,这些都是发现和花哨,但我们需要将此ID与articleSchema相关联,因此当我们在应用程序中调用该文章时,它将显示相关图像。
当用户点击submit时,我们创建/更新文章:
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();
});
}},
因此,我需要它做的是,当用户在创建一篇文章时点击submit时,调用我刚刚上传到模式的image部分的图像的ID。我尝试过在提交时执行readstream,但同样的问题是,我无法获得ID或文件名来关联它。
它们被存储在mongo数据库中,它创建了fs.files和fs.chunks,但对于我来说,在不知道ObjectId的情况下,我不知道如何获取数据并将其附加到模式,或者甚至只是将数据提取出来。
那么,如何从fs.files或fs.chunks中调用objectid来将其附加到模式呢?在模式中,我如何引用fs.files或块?所以它知道objectid与什么关联?
我可以提供更多的数据,如果我有的是模糊的,我有这样做的坏习惯。抱歉的。
发布于 2016-03-10 02:38:50
所以我最终解决了我的问题,可能不是最好的解决方案,但在我找到更好的解决方案之前,它是有效的。
在API中更改
res.status(200).json({"id":readStream.id});至
res.status(200).send(readStream.id);在我的组件中,我将状态设置为response.body,这将设置上传的图像的id的状态。因此,在主视图中,我引用了图像上传组件,并将视图的图像状态设置为组件的id状态,现在我在数据库中具有与新创建的文章相关联的id。
然后我遇到的问题是,它不知道要引用什么。因此,我将API URL附加到id,它的行为就像引用URL img一样,并正确地呈现图像。
再说一次,这可能不是最好的方法,事实上,我很确定它不是,但这是目前的工作,直到我可以正确地引用数据库,或创建一个新的组件,只是存储所有的图像在服务器上,并引用它们的方式,很像wordpress。
https://stackoverflow.com/questions/35873123
复制相似问题