我使用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?所以它知道目标与什么有关?
我可以提供任何数据,如果我有什么是模糊的,我有一个恶劣的习惯做到这一点。抱歉。