Annie Alan Annie Alan - 1 year ago 56
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 :


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;

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

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

    (callback) =>
      async.each(mongoose.models,(model,callback) =>

    (callback) =>
          (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');

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

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

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


  (err) => {
    if (err) throw err;

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

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download