Here I am using the official mongodb driver btw.
const { MongoClient, ServerApiVersion } = require('mongodb');
const CLient = new MongoClient(process.env.uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1});
const db = CLient.db("Discord").collection("Discord");
CLient.connect(err => {
//const db = CLient.db("Discord").collection("Discord");
console.log("Connected to the Database")
//CLient.close();
const prefix = await db.find({guildid: msg.guild.id});
await db.updateOne({guildid: msg.guild.id}, {$set: {prefix: newPrefix}});
if (!prefix) {
let prefix = db.insertOne({guildid: msg.guild.id, prefix: newPrefix})
return msg.channel.send(`Your server prefix is now ${newPrefix}`);
}
return msg.channel.send(`Your server prefix is now ${newPrefix}`);
});
msg is already defined here as a object btw and newPrefix is also defined. So the database connected successfully according to the logs. The error is thrown when the code is run
MongoServerError: BSON field 'update.apiVersion' is an unknown field this is the error msg. How can i fix this
I had the same problem. This is related to how you instantiate the client - i.e., this won't fail:
const Client = new MongoClient(process.env.uri);
Related
trying to get my code to connect to mongodb.
I have start mongo db compass, rund mongosh and mongod in cmd
add a new db to mongodb.
edit a new url to connect.
run npm start and get this and i dont connect to mongodb:
(node:14420) [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.
(Use `node --trace-warnings ...` to show where the warning was created)
my db.ts
import { MongoClient } from 'mongodb';
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'xxxxx';
// Create a new MongoClient
export async function initMongo() {
try {
const client = new MongoClient(url,{ useNewUrlParser: true });
await client.connect();
const db = client.db(dbName);
at the bottom of db
} catch (e) {
console.log('Cannot connect to MongoDB. Will retry in 10 seconds ...');
await new Promise<void>(resolve => {
setTimeout(() => resolve(), 10000);
});
console.log('Retrying...');
return await initMongo();
}
await client.connect
connect have a line right true.
Following the manual from npm mongodb webpage(https://www.npmjs.com/package/mongodb) I created in progect directory and then specified a database directory by typing mongod --dbpath=/data? then I launched this file:
app.js
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
and I got success, but folder data is still completely empty. What is wrong?
Actually, when you call "dbpath=/data" even being in your directory with this folder created, this command in Windows means that your db will be stored in folder "C:/ProgramFiles/mongodb/data". To specify your progects folder, use full path
I am trying to connect to MongoDB but I am getting the "Password contains unescaped characters" error. I have included the useNewUrlParser:true option but I still get the error
See my code below:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
connectDB().catch(err => console.log(err));
async function connectDB() {
await mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
})
.then(() => console.log("DB Connection Success"))
.catch((err) => console.log(err));
}
app.listen(8800, () => {
console.log("Backend Server is running");
});
Same problem here... solved with encodeURIComponent on the part of the string that had the password
const uri = "mongodb+srv://username:" + encodeURIComponent("pass#") + "#cluster.yijnb.mongodb.net/db?retryWrites=true&w=majority";
Maybe provide username and password as option:
const options = {
user: <username>,
pass: <password>,
authSource: "admin",
useNewUrlParser: true
};
mongoose.connect(process.env.MONGO_URL, options);
I solved it by changing the password as I tried using several fixes to help me connect with the initial password that contained ".".
I am building a RESTful BLogAPP where my stack is MEN
while connecting to mongo server i am getting this error
These were working But this happened
My Mongo file code
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = "mongodb://localhost/127.0.0.1:27017/Blog";
mongoose.connect(url ,{
useNewUrlParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", url);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
module.exports = mongoose;
My app.js
const mongoose = require("./server/mongoose");
It was resolved for me after remove server port from connection string. Replace mongodb connection string From
const url = "mongodb://localhost:27017/Blog";
To
const url = "mongodb://localhost/Blog";
I got the same error message and I've finally solved it. Try to leave it like this:
const url = "mongodb://localhost:27017/Blog";
I too got the same error while accessing MongoDB via mongoose.
The URI I set was MONGO_URI=mongodb://localhost:3000/myDB.
The port was wrong.
I solved it by correcting the Mongo URI.
MONGO_URI=mongodb://localhost:27017/myDB.
I'm new in the MEAN developing, I'm developing a simple app, and for my first step I'm trying to connect to my mongodb, so I installed node, express, morgan,mongodb, mongoose.
So here is my code in index.js:
const express = require('express');
const morgan = require('morgan');
const app = express();
const { MongoClient } = require('./database');
// Settings
app.set('port', process.env.PORT || 3000);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
// Routes
// Starting the server
app.listen(app.get('port'), () => {
console.log('server on port', app.get('port'));
});
and then the code on my database.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log("horrorrrrrr");
// perform actions on the collection object
client.close();
});
module.exports = MongoClient;
I also try this code that is on the mongodb page to connect to the application:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://duke:<password>#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Of course I change the password to the real one. Please keep in my today it's my first time I touch mongodb and also the MEAN full stack, and I spent too many hours stuck in this connection.
this is the error I get:
(node:5284) 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.
EDIT
#iLiA thanks for your reply ! I tried your code and ain't working, I will show you how I did it with the real password :
const url = 'mongodb+srv://duke:password#cluster0-dreyi.mongodb.net/test?retryWrites=true&w=majority';
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is not a problem with ${err.message}`);
process.exit(-1)
})
module.exports = mongoose;
and the error is :
there is not a problem with Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Kind regards,
I am confused about why do you downloaded both mongodb and mongoose but here is mongoose solution
const mongoose = require('mongoose');
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(()=>{
console.log('congrats, problem solved')
})
.catch((err)=>{
console.log(`there is a problem with ${err.message}`);
process.exit(-1)
})
EDIT:
As it seems you forgot to whitelist your IP address in mongo atlas.