Annie Alan Annie Alan - 5 months ago 20
Node.js Question

What data type should I use in order to store base64 string?

I have an image with base64 (e.g. data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QCcUGhvdG9zaG9w....)

how to save in the database using mongoose? what should be the type of the field in mongoose schema? Buffer?

Answer Source

The short answer is store as "Binary", for which in a mongoose schema you can use Buffer to do this.

The longer form is to demonstrate:

  • Read an image (or any binary data) from file
  • Base64 encode that data (just to show it can be done)
  • Turn back into Binary data from base64 ( just to show it can be done )
  • Store Binary data in the database
  • Read Binary data from the database
  • Ouput binary data to a new file

So the Schema Part is simple, just use Buffer:

var albumnSchema = new Schema({
  name: String,
  image: Buffer
})

Then all be are going to do is follow the process and put the binary data into the property and read it back out again.

Note though that if you are coming directly from a string with a MIME type on it like :

  data:image/png;base64,long-String

Just use a javascript .split() and take the second array index for the base64 string itself:

var string = "data:image/png;base64,long-String"
var bindata = new Buffer(string.split(",")[1],"base64");

Here's a listing with a complete demo in and out:

const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema,
      fs = require('fs');

mongoose.Promise = global.Promise;
mongoose.set('debug',true);
mongoose.connect('mongodb://localhost/test');

var albumnSchema = new Schema({
  name: String,
  image: Buffer
})

const Albumn = mongoose.model('Albumn', albumnSchema);


async.series(
  [
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    (callback) =>
      async.waterfall(
        [
          (callback) => fs.readFile('./burger.png', callback),

          (data,callback) => {
            // Convert to Base64 and print out a bit to show it's a string
            let base64 = data.toString('base64');
            console.log(base64.substr(0,200));

            // Feed out string to a buffer and then put it in the database
            let burger = new Buffer(base64, 'base64');
            Albumn.create({
              "title": "burger",
              "image": burger
            },callback)
          },

          // Get from the database
          (albumn,callback) => Albumn.findOne().exec(callback),

          // Show the data record and write out to a new file.
          (albumn,callback) => {
            console.log(albumn);
            fs.writeFile('./output.png', albumn.image, callback)
          }

        ],
        callback
      )


  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
)

And here's a burger.png to play with:

enter image description here