i've a problem in my nodejs mongoDB script, it look like that
const MongoClient = require('mongodb').MongoClient;
const dotenv = require('dotenv');
const test = require('assert');
dotenv.config();
const url = process.env.MONGO_URI;
async function main(){
MongoClient.connect(url, function(err, client) {
if (err) {
console.log(err);
}
else {
const adminDb = client.db().admin();
const mongoCommand = { copydb: 1, fromdb: "dbtest", todb: "newdbtest"};
adminDb.command(mongoCommand, function(commandErr, data) {
if (!commandErr) {
console.log(data);
} else {
console.log(commandErr.errmsg);
}
client.close();
});
}
});
}
main().catch(console.error);```
But when i run this script, i have an error not authorized on admin to execute command...
and i don't understand why my user from MongoDB Atlas can't perform this operation
Can you help me ?
Is that because i have a free cluster ?
Thanks in advance
Related
I have uploaded a few images in MongoDB but cannot retrieve the images. I'm new to Next js, can anyone explain how I can make a "/api/retrieve?fileName='...'" get API to retrieve images from the database. The handler is being executed first then the db connection message is showing.
import nc from "next-connect";
import mongoose from "mongoose";
import Grid from "gridfs-stream";
import { GridFsStorage } from "multer-gridfs-storage";
export const config = {
api: {
bodyParser: false,
},
};
Grid.mongo = mongoose.mongo;
let gfs;
const conn = mongoose.createConnection(
process.env.mongoURI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) {
console.err("file DB connection error", err);
process.exit();
}
console.log("file DB connected!");
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection("images");
}
);
export default async function handler(req, res) {
if (req.method === "GET") {
console.log("request query: ", req.query);
try {
const file = await gfs.files.findOne({ filename: req.query.filename });
const readStream = gfs.createReadStream(file.filename);
readStream.pipe(res);
} catch (error) {
res.send("not found");
}
}
}
Thanks in advance.
I want to use socekt.io for a new project I am building. I am using socket.io for a login component and will be using socket.io in the future to update pages like a chat app. I am also using mongoose to handle my mongodb connection. I am taking in a username, and returning a password to my front end to be bcryptjs compareSync hashed. The problem I am having is that whatever is returned to the front end is undefined. When I print out what is returned to the front end, it prints out the value I am looking for though. Something is going on between the backend emitting something, and the frontend receiving something but I don't know what is it exactly. Here is my code for the back end:
const express = require('express')
const socket = require('socket.io');
const http = require('http');
const router = require('./router');
const mongoose = require('mongoose');
let Player = require('../models/player.model');
require('dotenv').config();
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true,
useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('MongoDB database connection established successfully')
});
const io = socket(server);
io.on('connection', (socket) => {
console.log('We have a new connection');
socket.on('login', ({ username }, callback) => {
console.log(username);
Player.find({"username": username}, function (err, player) {
if(err) {
console.log("there has been an error"), {player: null}
}
socket.emit('id', { password: player[0]['password'].toString(), id : player[0]['_id']})
}) })})
app.use(router);
server.listen(PORT, () => console.log('Server is working'))
Here is my code for the front end:
const ENDPOINT = 'localhost:5000';
async function submitAccount (e) {
e.preventDefault();
socket.emit('login', { username });
socket.on("id", (response) => {
setPassword2(String(response['password']));
id = response['id']; console.log(id);
console.log(password2)
});
try {
if (bcrypt.compareSync(password, password2) == true) {
props.setCookie("id", id);
setAccess(true);
access2 = true;
console.log(access2)
console.log('works')
}
else {
setErrorType('Invalid Password')
setErrorMsg('There is an issue with your password. Please try again')
setOpenModal(true)
console.log(password);
console.log(password2);
}
}
catch {
setErrorType('Invalid Username')
setErrorMsg('This username does not exist. Please try another')
setOpenModal(true)
}
Thanks for the help!
When you do the socket.on, it should include the whole statement you are looking to change with the socket.io output. See below:
async function submitAccount (e) {
e.preventDefault();
socket.emit('login', { username });
socket.on("id", (response) => {
setPassword2(String(response['password']));
id = response['id']; console.log(id);
console.log(password2)
if (password2 != undefined) {
try {
if (bcrypt.compareSync(password, password2) == true) {
props.setCookie("id", id);
setAccess(true);
access2 = true;
console.log(access2)
console.log('works')
}
}
I am trying to move documents based on last update time into another remote db.
Currently trying to use $merge to implement the same.
But new database is created on same local connection and not on remote connection.
LOCAL_DB_NAME.aggregate([
{ $merge: { into: { db: "REMOTE_DB_NAME", coll:"COLLECTION_NAME" } }},
]).toArray();
Connection Initialization code:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://xxx:27017';
const dbName = 'local';
const url2 = 'mongodb://xxx:27017';
const dbName2 = 'remote';
var dbClient,dbClientRemote;
MongoClient.connect(url, async function(err, client) {
if(err){
console.log("->", err)
return
}
console.log("Connected successfully to server");
const db = client.db(dbName);
dbClient = client;
MongoClient.connect(url2, async function(err2, client2) {
if(err2){
console.log("->", err2)
return
}
console.log("Connected successfully to server2");
const db2 = client2.db(dbName2);
dbClientRemote = client2;
});
});
It's not possible. You can move into [different DB] collection only for the same instance (Standalone / Replica set).
I have to get the MongoClient object from mongoose connection object, so that I can reuse for Agenda or somewhere else where I need.
db.js
// Export the mongoose instance
module.exports = () => {
mongoose.Promise = global.Promise;
try {
console.log('DBURL:', dbConfig.url);
const { url, options } = dbConfig;
mongoose
.connect(url, options)
.then(() => console.log('DB Connected'), err => console.log(err, options));
mongoose.connection.on('connected', () => {
logger.log('info', 'Mongoose default connection opened');
});
mongoose.connection.on('error', (err) => {
// logger.log('error', 'Couldn't able to connect to MongoDB', err);
// Blow system on db error
logger.log('info', 'Mongoose default connection opened');
throw err;
});
mongoose.connection.on('reconnected', () => {
logger.log('info', 'Mongo connection reconnected', arguments);
});
mongoose.connection.on('disconnecting', () => {
logger.log('error', 'Mongoose connection disconnecting', arguments);
});
mongoose.connection.on('disconnected', () => {
logger.log('error', 'Mongoose connection disconnected', arguments);
});
} catch (e) {
console.log("Couldn't connect to mongo:", e);
}
return mongoose;
};
You can get the mongoClient with getClient() method as shown in the docs: getClient()
Basically you need to do something like this
const client = mongoose.connection.getClient()
So to use it with connect-mongo for example you could just export that from your db.js then import and use where needed.
//db.js
module.exports.client = mongoose.connection.getClient()
//app.js
const { client } = require('path to file')
const store = MongoStore.create({ client })
const mongoose = require("mongoose");
let options = { //Your options };
const mongoClient = new mongoose.mongo.MongoClient(URI, options)
config = require('./configs');
mongoose = require('mongoose');
module.exports = function() {
var db = mongoose.connect(config.db, config.mongoDBOptions).then(
() => {
console.log('MongoDB connected')
},
(err) => {
console.log('MongoDB connection error',err)
}
);
require('../app/models/xxx.server.model');
require('../app/models/yyy.server.model');
return db;};
You may get MongoClient Object by following this method:
const { MongoClient, ObjectID } = require('mongodb');
function(req, res) {
(async function mongo() {
let client;
try {
client = await MongoClient.connect(url, {useNewUrlParser: true});
debug('Connected correctly to server');
const db = client.db(dbName);
}
I'm learning about webtask.io and so I've coded a simple REST api (I'm not using Express.js here but maybe I should). It's a little webtask.io app that connects to an mlab MongoDB database and retrieves todos from a tasklist collection. The issue is that I'm getting this error:
{"code":404,"message":"unable to resolve jtn to webtask token","req_id":"1504385487318.83712"}"
Any idea how to fix this error? Here is a snippet of my code:
var MongoClient = require('mongodb').MongoClient;
...
module.exports =
function (ctx, req, res) {
// write the header and set the response type as a json
res.writeHead(200, { 'Content-Type': 'application/json' });
MongoClient.connect(ctx.data.MONGO_URL, function (err, db) {
if (err) {
res.writeHead(400, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(ERROR_RESPONSE.CONNECT_ERROR));
} else {
switch(req.method) {
case 'GET':
db.collection('tasklist').find({}).sort({"dateAdded" : -1}).toArray(function(err, docs) {
if (err) {
res.writeHead(400, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(ERROR_RESPONSE.GET_ERROR));
} else {
res.end(JSON.stringify(docs));
}
}); //toArray
break;
//post, delete, and put are in here
} //switch
} //else no error
db.close();
}); //Mongo connect
res.end();
} //export function
I decided to try using Express and now I'm able to run my little webtask.io without having to have a web token. I'm not sure why my first try required one and if I find that answer I will post it. Here is my working version:
/* express app as a webtask */
var MongoClient = require('mongodb').MongoClient;
var Express = require('express');
var wt = require('webtask-tools');
var app = Express();
var assert = require('assert');
var ObjectId = require('mongodb').ObjectId;
app.use(require('body-parser').json());
function doCRUD (crudType,req,res) {
MongoClient.connect(req.webtaskContext.secrets.MONGO_URL,function (err, db) {
if (err) {
res.send(JSON.stringify(err));
} else {
switch(crudType) {
case 'GET':
db.collection('tasklist').find({}).sort({"dateAdded" : -1}).toArray(function(err, docs) {
if (err) {
res.send(JSON.stringify(err));
} else {
res.end(JSON.stringify(docs));
}
}); //toArray
break;
case 'POST':
db.collection('tasklist').insertOne({"tasklist" : req.query.todo, "dateAdded" : new Date()}, function(err, r) {
assert.equal(null, err);
assert.equal(1, r.insertedCount);
});
break;
case 'DELETE':
db.collection('tasklist').deleteOne({_id: new ObjectId(req.query.id)},function(err){assert.equal(null,err)});
break;
case 'PUT':
//not implemented for this hack
break;
}
}
});
}
// GET
app.get('*', function (req, res) {
doCRUD('GET',req,res);
});
// POST
app.post('*', function (req, res) {
doCRUD('POST',req,res);
res.end();
});
// DELETE
app.delete('*', function (req, res) {
doCRUD('DELETE',req,res);
res.end();
});
// expose this express app as a webtask-compatible function*/
module.exports = wt.fromExpress(app);
This error appears if you do not specify a valid path.
Try this one for example :
https://wt-666ohgod666ohgod666ohgod666ohgod-0.run.webtask.io/antidisestablishmentarianism666