使用Mongoose将GridFS-Stream文件与Schema相关联

时间:2016-03-08 16:46:25

标签: javascript mongodb express mongoose gridfs-stream

我正在使用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");

我的网格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();
  });
}

},

所以我需要它做的是,当用户在创建文章时点击提交时,调用刚刚上传到我的模式的images部分的ID的ID。我已尝试在提交时执行读取流,但问题是我无法获取ID或文件名以便能够关联它。

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

那么如何从fs.files或fs.chunks中调出objectid以将其附加到模式?在模式中如何引用fs.files或块?所以它知道objectid与之相关联的是什么?

我可以提供更多的数据,如果我的模糊,我有一个讨厌的习惯。遗憾。

1 个答案:

答案 0 :(得分:1)

所以我最终解决了我的问题,可能不是最好的解决方案,但它一直有效,直到我能找到更好的解决方案。

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

相关问题