【问题标题】:Mongoose getter to convert image buffer to string? (Mongoose)Mongoose getter 将图像缓冲区转换为字符串? (猫鼬)
【发布时间】:2022-10-07 19:33:31
【问题描述】:

我创建了一个基于 ebay 的简单节点后端应用程序。我正在尝试制作一个反应前端应用程序来配合它。

用户可以出售一件物品,并可以提交一张照片来搭配它。该项目被添加到 mongodb 集合中,并使用 multer 添加照片。 “文件”字段下方是照片。

是否可以使用带有 mongoose 的 getter 将图像缓冲区转换为字符串以供前端使用?

非常感谢。

项目架构:

const mongoose = require('mongoose')

const itemSchema = new mongoose.Schema({
    title:{
        type:String,
        require:true,
        min:1,
        max:256
    },
    description:{
        type:String,
        require:true,
        min:1,
        max:1024
    },
    condition:{
        type:String,
        require:true,
        enum:['New','Used']
    },
    user:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        require:true
    },
    expiresAt:{
        type:Date,
        require:true
    },
    maxBid:{
        type:mongoose.Schema.Types.ObjectId,
        ref: 'Bid',
        require:true,
        default: undefined
    },
    file: {
        data: Buffer,
        contentType: String
      }
},
{ virtuals: true ,versionKey: false, id: false, timestamps: { createdAt: true, updatedAt: false } })

itemSchema.virtual('status').get(function () { 
    return this.expiresAt > new Date() ? 'Open to offers' : 'Completed'
});

itemSchema.virtual('timeLeft').get(function () { 
    const total     = Date.parse(this.expiresAt) - Date.parse(new Date())
    if (total < 0) return '00:00:00:00'
    const seconds   = String(Math.floor( (total/1000) % 60 )).padStart(2, '0')
    const minutes   = String(Math.floor( (total/1000/60) % 60 )).padStart(2, '0')
    const hours     = String(Math.floor( (total/(1000*60*60)) % 24 )).padStart(2, '0')
    const days      = Math.floor( total/(1000*60*60*24) )
    return `${days}:${hours}:${minutes}:${seconds}`
});

itemSchema.set('toJSON', { getters: true })
const Item = mongoose.model('Item', itemSchema, 'items');
module.exports = { Item };

显示可用项目的 get 方法:

router.get('/available', async(req,res)=>{
    const items = await Item.find(
        {expiresAt:{ $gt: new Date()}},{__v:0, description:0, createdAt:0})
        .sort({expiry_date: -1})         
        .populate({
            path:"maxBid",
            model:"Bid",
            options: { select: {"price":1}}})             
        .populate({
            path:"user",
            model:"User",
            options: { select: {"username":1}}})
    res.send(items)    
})

存储在 mongodb 上的项目:

可用项目路由返回的 JSON(当前只有一个,并且缓冲区数组替换为缓冲区数组替换为“BUFFERDATA”):

[
  {
    "file": {
      "data": {
        "type": "Buffer",
        "data": ['BUFFERDATA']
      },
      "contentType": "image/jpeg"
    },
    "_id": "633db529bf13d1cb7f9ba7f0",
    "title": "faberge egg",
    "condition": "Used",
    "user": {
      "_id": "62588f89dbc142710869a615",
      "username": "Olga"
    },
    "expiresAt": "2022-10-30T21:30:00.000Z",
    "status": "Open to offers",
    "timeLeft": "24:09:16:44"
  }
]

【问题讨论】:

    标签: javascript node.js express mongoose multer


    【解决方案1】:

    我强烈建议您将图像的路径而不是其数据存储在数据库中。 将图像直接存储在数据库中会导致数据库变得过于庞大和缓慢。

    您可以使用Multer 在磁盘上存储和重命名图像文件,然后使用其路径将其存储在数据库中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2019-07-29
      相关资源
      最近更新 更多