Estoy haciendo una conexion a mongodb por medio de la libreria de mongoose, y al iniciar el servidor y consumir una ruta me aparece esto:
(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.
Asi que coloque esta opcion useNewUrlParser: true donde mongoose hace la conexion, pero no funciono.
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')
}
Este es mi AuthController, donde intento crear un documento en mi colección:
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})
}
}
}
Modelo User, aqui asigno los campos de mi documento:
'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)
Esta es la configuracion de conexion a 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
Graciass.