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());
Related
I am trying to create web services using node js,express and mongoose.
this is my app.js file
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
GetData = require('./models/women');
mongoose.connect('mongodb://localhost/shopping');
var db = mongoose.connection;
app.get('/api/getCategories',function(req,res){
GetData.getCategory(function(err,getCategory){
if (err) {
throw err;
}
res.json(getCategory);
});
});
app.get('/',function(req,res){
res.send('Hi i am Madhura. Nice to Meet u. lets start creating web services');
});
app.listen(3000);
console.log('connected to Port 3000');
this is my women.js file
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = module.exports = mongoose.model('',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
I am unable to understand this line
var Category = module.exports = mongoose.model('',categorySchema);
I have left this ' ' blank because I wanted to know what parameter is passed here
I watched a video about this, and could not find a conclusion. however, I simply followed the video and run the code. but my output is coming to be a null JSONArray "[]". Please tell me what am i doing wrong.
var mongoose = require('mongoose');
var categorySchema = mongoose.Schema({
name:{
type: String,
required: true
}
});
var Category = mongoose.model('Category',categorySchema);
module.exports.getCategory = function(callback,limit){
Category.find(callback).limit(limit);
}
The part you have made '' contains the mongoose model name that you can use to refer the respective MongoDB collection. you can imagine a model name as replacement of db.collectionname for MongoDB. I have updated the codebase
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);
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.
Why is Mongoose showing the deprecated warning after I have set the promise library?
Countless posts (example #1, example #2, etc.) say to set mongoose.Promise = global.Promise; to resolve this warning. I have even done it myself in the past! However, nothing I do prevents Mongoose from complaining about the promise library:
(node:54561) DeprecationWarning: Mongoose: mpromise (mongoose's default
promise library) is deprecated, plug in your own promise library instead:
http://mongoosejs.com/docs/promises.html
I'm using v4.8.7 with the following code:
var bodyParser = require('body-parser'),
config = require('./config'),
data = require('./data'),
express = require('express')
mongoose = require('mongoose'),
routes = require('./routes');
mongoose.Promise = global.Promise;
var db = mongoose.connection;
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(routes);
db.once('open', function() {
console.log('Database connected!');
data.seeds.doSeed(function(){
app.listen(3000, function() {
console.log('Mongo example listening on port 3000!');
});
});
});
mongoose.connect(config.db.uri, config.db.options);
You are using the underlying MongoDB driver, from the documentation
Promises for the MongoDB Driver
The mongoose.Promise property sets the promises mongoose uses. However, >this does not affect the underlying MongoDB driver. If you use the >underlying driver, for instance Model.collection.db.insert(), you need to >do a little extra work to change the underlying promises library. Note >that the below code assumes mongoose >= 4.4.4.
var uri = 'mongodb://localhost:27017/mongoose_test';
// Use bluebird
var options = { promiseLibrary: require('bluebird') };
var db = mongoose.createConnection(uri, options);
Band = db.model('band-promises', { name: String });
db.on('open', function() {
assert.equal(Band.collection.findOne().constructor, require('bluebird'));
});
I think this is a answer you are asking for.
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');
}
});