Mongoose Promise error - node.js

This is the error which is still being thrown when saving even after adding native promise.
(node:5604) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://127.0.0.1/optimusCP')
.then(function () {
console.log('Connected to MONGOD !!');
}).catch(function (err) {
console.log('Failed to establish connection with MONGOD !!');
console.log(err.message);
});
I have tried both bluebird & q, still haven't found a fix for this.
Below is the code when I save this, the following deprecation warning shows up..
var user = new User();
user.email = req.body.email;
user.password = hash;
user.save()
.then(function (user) {
console.log(user);
})
.catch(function (err) {
console.log(err);
});
This error is happening on the new version of mongoose which is 4.8.1, but working fine on 4.7.6 mongoose version.

Despite using mongoose.Promise = global.Promise; before mongoose.connect(...), I had the same warning.
I discovered, that I initialized mongoose connection in one file:
import mongoose from 'mongoose';
...
// Connect to MongoDB
mongoose.Promise = global.Promise;
mongoose.connect(mongoUri, mongoOptions);
mongoose.connection.on('error', (err) => {
console.error(`MongoDB connection error: ${err}`);
process.exit(1);
});
But I imported mongoose in another file too (where mongoose scheme was described), so I added mongoose.Promise = global.Promise; in second file too, as a result of it, the warning disappeared.
import mongoose, { Schema } from 'mongoose';
mongoose.Promise = global.Promise;
const UserSchema = new Schema({ ... });
May be you have the same case.

I've had success getting rid of the message with this
mongoose.Promise = Promise;

I have used bluebird for using promise with mongoose model functions node v6.9.4 :
mongoose.Promise = require('bluebird');

Upgrading Mongoose from 4.8.1 to 4.9.1 solved my problem.

Related

MongooseError: Operation `products.insertOne()` buffering timed out after 10000ms

I am using Youtube tutorial about API using MongoDB and mongoose. However,I am keep getting this error whenever I do POST something on Postman.
"MongooseError: Operation products.insertOne() buffering timed out after 10000ms"
const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
client.close();
});
I am using visual studio code 1.57.1 and the version of MongoDB is 4.4.10.
Please can someone help me??
This will help you.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test')
.then(()=>console.log("DB Connected"))
.catch((err)=>console.log(err))
if you're using the mongoose model use this connection setting or as mentioned in mongoose website
You need to use mongoose to create a connection with the MongoDB. Add the following code to your app.js or server.js first.
const mongoose = require("mongoose");
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
console.log("Connected successfully");
});
Use this to open a connection and then proceed with the insert operation.

Mongoose Multi Connection with Fastify

I am trying to use multiple database connections in fastify with mongoose.
for single db code looks like
const mongoose = require('mongoose');
const fastifyPlugin = require('fastify-plugin')
mongoose.Promise = Promise; // Set mongoose to use ES6 Promises.
const reconnectTimeout = 5000; // ms.
const db = mongoose.connection;
async function dbConnector1(fastify, options) {
const conn1 = mongoose.connect("mongodb://localhost/db1", {
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false
})
.then(() => console.log( 'Connection to DB1 successful'))
.catch((err) => console.error(err));
};
module.exports = fastifyPlugin(dbConnector1,{
name: 'DB1'
})
I have put the above code in conn1.js
I have created a similar connection with different db in conn2.js and in index.js I am registering the db plugin as follows
await fastify.register(require('./src/db/conn1'))
await fastify.register(require('./src/db/conn2'))
I get the following error -
MongooseError: Can't call openUri() on an active connection with different connection strings. Make sure you aren't calling mongoose.connect() multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections

What should I do to connect mongoose 5.8 with mongodb?

I'm using mongoose. 5.8.2 and following a tutorial where the person is running mongoose on v3.5. I know there has been changes like useNewUrlParser has been deprecated and instead we use useUnifiedTopology but the problem is that whenever I use useUnifiedTopology then I get the error that it has been deprecated. Please have a look below and let me know what am I doing wrong
const mongoose = require('mongoose')
mongoose.createConnection('mongodb://127.0.0.1:27017/task-manager-api', {
useUnifiedToplogy: true,
useCreateIndex: true
});
const User = mongoose.model('User', {
name: {
type: String
},
age: {
type: Number
}
})
const me = new User({
name: 'Lallan',
age: '27'
})
me.save().then(() => {
console.log('Done')
}).catch((error) => {
console.log('error', error)
})
and the following is the error and I'm not able to connect mongoose with mongodb
the options [useUnifiedToplogy] is not supported
(node:6573) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:6573) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
What should I do to connect mongoose with mongodb?
The most default connection will be to just { useNewUrlParser: true }. You can use createConnection()(for multiple pools) as well as connect()(single pool).
From MDN a basic example will be:
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, { useNewUrlParser: true });
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
Also,
If you need to create additional connections you can use
mongoose.createConnection(). This takes the same form of database URI
(with host, database, port, options etc.) as connect() and returns a
Connection object.
like,
const db = mongoose.createConnection('mongodb://user:pass#localhost:port/database', opts);
Maybe try giving it this way,
const mongoose = require('mongoose');
let db_uri = "'mongodb://localhost:27017/mydb"
mongoose.connect(db_uri, {
useNewUrlParser: true,
useUnifiedTopology : true
});
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);

TypeError: Cannot read property 'on' of undefined in node js and mongoose

I am getting an error when i run my application.
The error:
MongoDB.on('error', function(err) { console.log(err.message); });
TypeError: Cannot read property 'on' of undefined
...
I tried to comment that part of the code out to see if i have anymore similar errors and found another same one. ( This time the word "once" )
The code:
var mongoURI = "mongodb://localhost/chatapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
It would be really great if anyone could help me solve this :(
I searched the internet and found nothing helpful.
var mongoose = require('mongoose');
var mongoURI = "mongodb://localhost/chatapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
also before running the application in your terminal type npm install mongoose --save
Try this:
const mongoose = require('mongoose');
mongoose.connect(mongoURI);
mongoose.connection.once('open',()=>{
console.log('Connected to db');
});
The message is pretty clear. MongoDb is undefined.
Speaking on your MongoDb variable. Should be mongoDb with lowercase. It is one instance.
Anyway, the problem is in mongoose.connect(mongoURI).connection. Debug from there.
const config = require('../config');
const Mongoose = require('mongoose');
Mongoose.connect(config.dbURI);
Mongoose.connection.once('open',()=>{
console.log('Connected to db');
});
it helps me.

Mongoose v4.8.7 warns about Promise AFTER setting it

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.

Resources