How to connect to the database:mongoose? - node.js

Below is my code:The folder and filename is : gridFs/storeAudio.js.And the code is in storeAudio.js
var mongoose = require('mongoose');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
//establish mongoDB connection
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');
});
});
now in the cmd inside the gridFs file I am running the command node storeAudio.js to create the database with the collection.But the following error is displayed below in the screenshot attached:
Note:I ran the following commands before:npm install gridfs-stream,npm install mongoose.
Please let me know if any more inputs are needed.

Related

Gridfs and mongoose file upload

I have ran into a problem with gridfs file upload.
Basically I get this bizzare error and I have yet not found solution for solving this problem.
Here is my code that should deal with file upload:
var path = require('path');
var router = require('express').Router();
var mongoose = require('mongoose');
var serverConfig = require('../config.js');
var multiparty = require('connect-multiparty')();
var fs = require('fs');
var GridFs = require('gridfs-stream');
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
router.post('/upload', multiparty, function(req, res){
console.log("file was posted");
var writestream = gfs.createWriteStream({
filename: req.files.file.name + Date.now(),
mode: 'w',
content_type: req.files.file.mimetype,
metadata: req.body
});
fs.createReadStream(req.files.file.path).pipe(writestream);
writestream.on('close', function(file){
res.status(200).json(file);
})
})
When trying to run my code, I get this error:
if (!db) throw new Error('missing db argument\nnew Grid(db, mongo)');
^
Error: missing db argument
new Grid(db, mongo)
Im using Mongoose version 4.11.12 and Gridfs-stream version 1.1.1
Does anybody know what should be done to get this thing working?
Looks like mongoose.connection.db is not pulling in the database name as it maybe missing on the connection string, your connection string should look like 'mongodb://username:password#host:port/database?options...' where database is the database you want to connect to.
alternatively you can just replace
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs(db, mongoDriver);
with
var mongoDriver = mongoose.mongo;
var gfs = new Gridfs("myDatabase", mongoDriver);

gridfs-stream and mongoose >= 4.11.0 connection settings

I have been using gridfs-stream with older versions (<4.11.0) of mongoose with the following settings:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
mongoose.connect(connectionString);
grid.mongo = mongoose.mongo;
var gfs = grid(mongoose.connection.db);
All works fine with these settings. After the update to mongoose 4.11.11 the mongoose connection setting should be changed to (3rd line):
mongoose.connect(connectionString, {useMongoClient: true});
However, now mongoose.connection.db is no longer defined. How should the above code be changed to make it work again? Many thanks.
I found a solution which makes use of deasync and with minimal changes to all my existing code. However it does not look ideal so any suggestions will be greatly appreciated:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
var deasync = require("deasync");
//Connect to mongodb
mongoose.Promise = global.Promise;
mongoose.connect(connectionString, {useMongoClient: true});
//Get the connection setting
var getConnDb = function () {
var connDb;
mongoose.connection.then(function (conn) {
connDb = conn.db;
});
while (connDb === undefined) {
deasync.runLoopOnce();
}
return connDb;
};
//Set gridfs-stream connection
grid.mongo = db.mongo;
var gfs = grid(getConnDb());

TypeError: Object #<MongoClient> has no method 'db' solution vs Documentation

While going through a mongodb tutorial, I ran into an issue with this configuration:
var MongoClient = require('mongodb').MongoClient;
var mongoClient = new MongoClient(new server('localhost', '27017', {'native_parser': true}))
var db = mongoClient.db('test');
TypeError: Object # has no method 'db'
Eventually, I was able to solve it using mongodb server
var server = require('mongodb').Server,
Db = require('mongodb').Db;
var db =new Db('test', new server('localhost', '27017', {'native_parser': true}));
db.open(function(err, res){
app.listen(8080);
console.dir('app started on 8080');
});
However, the documentation says "Server should not be used, use the MongoClient.connect."
Based on this, I'd like to know when is the appropriate time to use the server?
Here is an example on how to use it in regards to the deprecation present in 2.0 and your setup and usage of callbacks instead of promises:
var mongoDB = require('mongodb');
var theDB = null;
mongoDB
.MongoClient
.connect('mongodb://localhost:27017/test', null, function(err, db) {
if (err) {
console.error(err);
} else {
theDB = db;
app.listen(8080);
console.dir('app started on 8080');
}
});

node.js mongo db write concern

I am running node.js 10.22, windows 8 and mongodb not sure what version, but I just downloaded it today, when I run my code I am getting a message, please ensure you set the default write concern, I am trying to follow a YouTube video, and there is mention of this, and I am finding little about it on the internet, from what i found, when I set the db i should set j:true, or safe : true/false, but neither not working for me. I do get the console log that I'm connected and the host and port, but then I get the write concern message and can't type or do anything.
var mongo = require('mongodb');
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodeintro", new mongo.Server(host,port,{Fsync: true}));
db.open(function(error){
console.log("we are connected"+host + port);
})
Tried this all type of ways as well, still no luck, best i did was get back to the db write concern message, but was not able to even connect this time. What I'm really looking for is to be able to insert anything in mongo db, and i can figure out the rest.
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var host = "127.0.0.1";
var port = mongo.DEFAULT_PORT;
ArticleProvider = function(host, port) {
this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(error){
if(error){
console.log(error)
}
else{
console.log(port,host)
}
});
};
ArticleProvider(host,port)
When using mongodb-native directly, you should now use MongoClient.connect to open a database connection pool. It will set a default write concern for you.
var mongodb = require('mongodb');
mongodb.MongoClient.connect('mongodb://localhost/nodeintro', function(err, db) {
// db is your open nodeintro database connection pool here
});
MongoClient was a somewhat recent addition so the tutorial you're working from likely pre-dates it.
If you use {w:1} parameter in your insert or update operation, you might give this error. To overcome you can use {journal:true} parameter in your db settings.
For instance;
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON;
var db = new Db('Your DB Name', new Server('192.168.170.128', 27017), { journal : true });
db.open(function(err, db) {
var collection = db.collection('user');
collection.findOne({'_id':req.session.User._id}, function(err, user){
// some codes what do you want
collection.save( user, {w: 1}, function(err, user_id) {
// just close the db connection
db.close();
});
});
});

node.js require("mongodb") throws an exception

I am a newbie to node.js (but 10 years experience with C#)
I have the following code
var http = require("http");
var url = require("url");
var path = require('path');
var fs = require("fs");
var express = require("express");
var mongo = require("./node_modules/mongo");
var Server = mongo.Server;
var Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('mydb', server);
I get this exception:
Error: Cannot find module './node_modules/mongo'
at Function.Module._resolveFilename (module.js:338:15)
I also tried:
var mongo = require("mongo");
Try this instead:
var mongodb = require('mongodb');

Resources