【问题标题】:How to get the ID of the uploaded file in GridFs to associate with another model如何在 GridFs 中获取上传文件的 ID 以与另一个模型关联
【发布时间】:2020-07-28 13:40:55
【问题描述】:

我创建了一个 GridFS 并使用它上传了一张图片:

app.post("/upload", upload.single("photo"), function(req, res) {
res.redirect("/images");
})

我为用户准备了另一个模型:

var userSchema = new mongoose.Schema({
username: String,
password: String,
posts: [
  {
    type: mongoose.Schema.Types.ObjectId,
    ref: "fs"
  }
 ]
});

我想将 GridFS 中的图像与登录的用户相关联。我可以得到用户ID。但我想知道如何获取上传图片的 id。如果可能,请详细说明。我还是个菜鸟。谢谢

【问题讨论】:

    标签: javascript mongodb mongoose gridfs


    【解决方案1】:

    上传的文件/照片的详细信息附加到请求对象中,您可以使用 req.file 访问它

    例如,要获取上传图片的 id,您可以这样做

    app.post("/upload", upload.single("photo"), function(req, res) {
        const id = req.file.id;
        res.redirect("/images");
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多