I have created the database and written the mp3 file in the db.Now I have created a server and used the router using express.But I am unable to see the response.It is displayed below.
My code is as follows:
server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var morgan = require('morgan');
var bodyParser = require('body-Parser');
var methodOverride = require('method-override');
var cors = require('cors');
mongoose.connect('mongodb://localhost/aHolyBoly');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
//res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var Songs = mongoose.model('Songs', {
title: String
});
app.get('/api/songs', function (req, res) {
console.log("fetching songs...");
Songs.find(function (err, songs) {
if (err)
res.send(err)
res.json(songs);
//console.log('Songs',+JSON.stringify(Songs));
});
});
app.listen(8080);
console.log("App listening on port 8080");
How can I see the response in the console.i.e my songs.mp3 file?
storeAudio.js
var mongoose = require('mongoose');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
//establish mongoDB connection
mongoose.Promise = global.Promise;
var conn = mongoose.createConnection('mongodb://localhost:27017/aHolyBoly');
conn.once('open',function(){
var gfs = Grid(conn.db);
// var db = new mongo.Db('aHolyBoly', new mongo.Server("127.0.0.1", 27017));
//var gfs = Grid(db, mongo);
var writeStream = gfs.createWriteStream({
filename:'song1.mp3'
});
fs.createReadStream('../list/hero.mp3').pipe(writeStream);
writeStream.on('close',function(file){
console.log(file.filename +'Written to db');
});
});
Points: 1.)I have stored the mp3 file in the database using gridFs-stream.
2.)Now I want to create an API so that I can host my server on it and my frontend uses that data with the help of API.
3.) The frontend will only fetch the data i.e) mp3 file.
What you must understand is when you use mongo's GridFS, it will create two collection namely fs.files and fs.chuncks and what ever other models you created do not have your file rather what you can do is to link those files in your model. If you are willing(may be for now) to receive only one file that you have stored with filename song1.mp3 the below stated code will work for you. Hope this helps!
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var morgan = require('morgan');
var bodyParser = require('body-Parser');
var methodOverride = require('method-override');
var cors = require('cors');
mongoose.Promise = global.Promise
var conn = mongoose.createConnection('mongodb://localhost/aHolyBoly');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
let gfs;
conn.once('open', function () {
gfs = Grid(conn.db);
});
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
//res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//song model should not be created like this
//var Songs = mongoose.model('Songs', {
// title: String
//});
app.get('/api/songs', function (req, res) {
console.log("fetching songs...");
//read from mongodb
var readstream = gfs.createReadStream({
filename: 'song1.mp3'
});
// set response header
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
});
readstream.pipe(res);
});
app.listen(8080);
console.log("App listening on port 8080");
To make clear on how linking a file to a model can be done, I have provided some code below:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
const UserFile = new Schema({
username: { type: String, unique: true}
file: { type: String }
})
// create the model to export
var UserFileModel = mongoose.model('UserFile', UserFile)
module.exports = schemaModel
Suppose, you have stored a file for one user. And you stored that filename in file field of UserFileModel with the corresponding username. Then, you can easily get file of corresponding user in following route as below:
var UserFileModel = require('path-to-UserFileModel');
router.get('/api/user/file/:username', function (req, res) {
UserFileModel.findOne({username: req.params.username}, function(err, doc){
//read from mongodb
var readstream = gfs.createReadStream({
filename: doc.file
});
// set response header
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
});
readstream.pipe(res);
})
});