I am making a connection to mongodb through the mongoose library, and when I start the server and consume a route, this appears:
(node:3500) 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. (Use node --trace-deprecation ...
to show where the warning was created) (node:3500) [MONGODB DRIVER] Warning: 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.
So I put this option useNewUrlParser: true where mongoose makes the connection, but it didn't work.
MongoseeProvider.js
_registerMongoose () {
this.app.singleton('Adonis/Addons/Mongoose', function (app) {
const Config = app.use('Adonis/Src/Config')
let connectionString = Config.get('database.mongodb.connectionString', null)
const {
host = 'localhost',
port = 27017,
database = 'test',
user = null,
pass = null,
options = {useNewUrlParser: true}, //Solo modifique esta linea para agregar el useNewUrlParser
debug = false
} = Config.get('database.mongodb.connection')
const auth = user ? `${user}:${pass}@` : ''
if (!connectionString) {
connectionString = `mongodb://${auth}${host}:${port}/${database}`
}
Mongoose.Promise = global.Promise
Mongoose.set('useCreateIndex', true)
Mongoose.connect(connectionString, options)
if (debug) {
Mongoose.set('debug', true)
}
return Mongoose
})
this.app.alias('Adonis/Addons/Mongoose', 'Mongoose')
}
This is my AuthController, where I try to create a document in my collection:
async register ({ request, response }) {
const data = await MongoUser.find({})
const IDlatest = data.length + 1
const id = IDlatest.toString()
const rules = {
nombre: 'required|string',
apellido: 'required|string',
password: 'required|string',
correo: 'required|string',
}
const validation = await validate(request.all(), rules)
if(validation.fails()){
return validation.messages()
} else {
var crypto = require("crypto");
var pin = crypto.randomBytes(20).toString('hex');
try{
const { nombre ,apellido, password, correo } = request.only([
'nombre',
'apellido',
'password',
'correo'
])
await MongoUser.create({
id: id,
nombre: nombre,
apellido: apellido,
password: password,
correo: correo,
pin: pin
})
return response.status(201).json({
message: "User creado correctamente",
})
} catch (e) {
return response.status(400).send({'Error': e})
}
}
}
User model, here I assign the fields of my document:
'use strict'
/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use('Hash')
const BaseModel = use('MongooseModel')
const mongoose = use('Mongoose')
const {Schema} = mongoose
const UserSchema = new Schema(
{
id: Number,
nombre: String,
apellido: String,
password: String,
correo: String,
pin: String,
}
)
class User extends BaseModel {
static boot () {
super.boot()
/**
* A hook to hash the user password before saving
* it to the database.
*/
this.addHook('beforeSave', async (userInstance) => {
if (userInstance.dirty.password) {
userInstance.password = await Hash.make(userInstance.password)
}
})
}
/**
* A relationship on tokens is required for auth to
* work. Since features like `refreshTokens` or
* `rememberToken` will be saved inside the
* tokens table.
*
* @method tokens
*
* @return {Object}
*/
tokens () {
return this.hasMany('App/Models/Token')
}
}
UserSchema.loadClass(User)
module.exports = mongoose.model('User',UserSchema)
This is the connection configuration to mongodb:
mongodb: {
connectionString: Env.get('MONGO_CONNECTION_STRING', 'localhost'),
connection: {
host: Env.get('MONGO_HOST', 'localhost'),
port: Env.get('MONGO_PORT', 27017),
user: Env.get('MONGO_USER', ''),
pass: Env.get('MONGO_PASSWORD', ''),
database: Env.get('MONGO_DATABASE', 'adonis'),
options: {
// All options can be found at http://mongoosejs.com/docs/connections.html
},
debug: false
}
},
.env
MONGO_CONNECTION_STRING=mongodb://localhost:27017/adonismongo
MONGO_CONNECTION=mongodb
MONGO_PORT=27017
MONGO_USER=
MONGO_PASSWORD=
MONGO_DATABASE=adonis
Thank you.
ISSUE
The problem is that you are overriding the value of
options
with an empty object. You currently have the following:However, your object
mongodb.connection
contains the following:As you can see the value of
options
is an empty object that overrides the value you want to give it in yoursingleton
.In the code above I show you that the options you have on your object
options
insidemongodb.connection
override what you put in the assignment.SOLUTION
The modification must be done in your object called
mongodb
in the objectconnection
on the fieldoptions
and not in where you currently have it.Therefore what you should do is write the value in the object
options
ofmongodb.connection
:This way, when you run the code, the object
options
in yoursingleton
will contain the correct values:I hope this helps you solve the problem.