0

我正在使用 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与什么相关联?

我可以提供更多数据,如果我所拥有的数据含糊不清,我有一个讨厌的习惯。对不起。

4

1 回答 1

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

于 2016-03-09T18:38:50.323 回答