简体   繁体   中英

Why is my buffer automatically converted to a nested array

My buffer format is being changed while trying to retrieve it from the MongoDB database, I'm not sure which step of the process is changing it.

I defined the mongoose schema as a buffer:

var mealSchema = mongoose.Schema({
  picture: Buffer, 

It looks like a what I expected in the database, a normal buffer:

{ "_id" : ObjectId("5691d1f73131c0db2b056447"), "picture" : BinData(0,"/9j/4TcORXhpZgAASUkqAKw2AA....

This is the code I used to send the buffer back to the client:

findAllMeals({})
      .then(function(meals) {
        res.send(200, meals);

This is how the client is receiving it back :

    Object {type: "Buffer", data: Array[86690]}
[0 … 9999]
[10000 … 19999]
[20000 … 29999]
[30000 … 39999]
[40000 … 49999]
[50000 … 59999]
[60000 … 69999]
[70000 … 79999]
[80000 … 86689]
length: 86690

It became an array of arrays, it's being stored as a buffer, and being send back an nested arrays. I also tried converting it to base64 in angular to see if it would convert it, it didn't. I changed the storage data type in the schema to string, it didn't change anything, There's isn't much else I can think of changing to troubleshoot.

It's not an array of arrays, it's a Buffer object with a big data array (console.log splits it to ease the logging). One solution would be to exclude the pictures and then have a different route to fetch the picture for a specific meal (because express can deal with buffers automatically ):

// first route, exclude pictures
app.get('/meals', function(req, res, next) {
  findAllMeals({}, {
      picture: 0
    })
    .then(function(meals) {
      res.send(200, meals);
    });
});

// second route to fetch the picture of a meal
app.get('/meal_picture/:mealId', function(req, res, next) {
  findOneMeal({
    _id: req.params.mealId
  }).then(function(meal) {
    res.status(200).send(meal.picture);
  });
});

Then, in your html, you can simply write:

<img src='/meal_picture/5691d1f73131c0db2b056447'></img>

Side note, res.send(200, meals) is deprecated, use res.status(200).send(meals) .

so I got it to work by changing the data type in the schema to

picture: {data: Buffer, contentType: String}, 

then in the client side I converted the base

<img ng-src="data:image/JPEG;base64,{{meal.picture}}"/>

and I managed to keep everything in the same REST request !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM