2016-03-08 88 views
0

我使用Mongoose,Express和GridFS-Stream为我的应用程序编写了一个API。我有该商品的模式,用户将创建:将GridFS-Stream文件与Mongoose的Schema关联

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"); 

和我的格子-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关联,所以当我们在应用中调用该文章时,它将显示关联的图像。

上的一篇文章中我们创建/更新,当用户点击提交:

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,图片的我刚刚上传当用户在创建文章时提交提交到我的模式的图像部分。我试过在提交时做一个readstream,但是再一次,问题是我无法获得ID或文件名,以便能够将其关联。

他们得到存储在mongo数据库中,它创建fs.files和fs.chunks,但对于我的生活,我无法弄清楚如何获取该数据并将其附加到架构,或者甚至在不知道ObjectId的情况下获取数据。

那么如何从fs.files或fs.chunks中调用objectid将其附加到模式?在模式中我如何引用fs.files或chunk?所以它知道目标与什么有关?

我可以提供任何数据,如果我有什么是模糊的,我有一个恶劣的习惯做到这一点。抱歉。

回答

0

所以我最终解决了我的问题,可能不是最好的解决方案,但它的工作,直到我可以得到一个更好的解决方案。

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一样。