How do I connect to a Mongodb?
I am trying to read the contents of a collection called "student".
onsole.log("001");
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb').MongoClient;
const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
console.log("003");
async function run() {
console.log("004");
client.connect();
const db = client.db("blah")
console.log("005");
const results = db.student.find()
console.log("006")
console.log(results)
console.log("007")
}
//call function
run()
This works to,
console.log("005");
But not,
console.log("006");
So there must be a problem with,
const results = db.student.find()
But at https://www.guru99.com/mongodb-query-document-using-find.html it says to do it like this.
Thanks,
Related
I currently have the following code, which saves the temp file to public/files I have tried to understand the MongoDB GridFS documentation but with no success.
I am wondering how do I get the files to save inside MongoDB GridFS instead of my public/file directory
I am aware I am missing the part where I need to send the uploaded file to mongodb - this is the part I don't know how to do.
In mongodb example they say to do something like:
fs.createReadStream('./myFile').pipe(
bucket.openUploadStream('myFile', {
chunkSizeBytes: 1048576,
metadata: { field: 'myField', value: 'myValue' },
})
);
however I am not using FS or do I need to upload the file to the temp and then do the fs
import formidable from 'formidable';
import { MongoClient, ObjectId } from 'mongodb';
var Grid = require('gridfs-stream');
export const config = {
api: {
bodyParser: false,
},
};
export default async (req, res) => {
const uri = process.env.MONGODB_URI;
let client;
let clientPromise;
const options = {};
client = new MongoClient(uri, options);
clientPromise = client.connect();
const clients = await clientPromise;
const database = clients.db('AdStitchr');
var gfs = Grid(database, client);
gfs.collection('uploads');
const form = new formidable.IncomingForm();
form.uploadDir = 'public/files';
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
var file = files.file;
console.log(JSON.stringify(file));
try {
const newFile = File.create({
name: `files\${file.newFilename}.mp3`,
});
res.status(200).json({ status: 'success' });
} catch (error) {
res.send(error);
}
});
};
I need to query mongo inside my Cypress tests to basically see if my POST is updating some fields, but I don't see a npm package for it like there is for sql server. Googling it I only see documentation and examples on how to seed the db.
Any thoughts, comments?
Thank you
Take a look at this post: https://glebbahmutov.com/blog/testing-mongo-with-cypress/
The gist of it:
-- plugins/index.js
/// <reference types="cypress" />
const { connect } = require('../../db')
module.exports = async (on, config) => {
const db = await connect()
const pizzas = db.collection('pizzas')
on('task', {
async clearPizzas() {
console.log('clear pizzas')
await pizzas.remove({})
return null
},
})
}
-- db.js
const { MongoClient } = require('mongodb')
const uri = process.env.MONGO_URI
if (!uri) {
throw new Error('Missing MONGO_URI')
}
const client = new MongoClient(uri)
async function connect() {
// Connect the client to the server
await client.connect()
return client.db('foods')
}
async function disconnect() {
// Ensures that the client will close when you finish/error
await client.close()
}
module.exports = { connect, disconnect }
Change the line await pizzas.remove({}) to whatever query you want to run, I'll assume you know how to get the result of the query and assert it.
I am trying to use Mongoose find query to get the complete list of documents held in my mongodb. However for some reason, the query stopped working and hasn't worked since. I believe all my code is correct, and its not giving me any error messages either.
Routes\image.js
const router = require('express').Router();
let imageModel = require('../Models/image');
router.get('/collection',(req,res) => {
imageModel.find({},(err,data) => {
if(err) {
res.status(500).json({msg:"Cant find collection",err})
} else {
res.send(data);
}
})
})
module.exports = router;
Models \ image
let mongoose = require('mongoose');
const Schema = mongoose.Schema;
let imageSchema = new Schema({
name:String,
desc:String,
imgUrl:String
});
let model = new mongoose.model('Image',imageSchema);
module.exports = model;
index.js
const express = require('express');
const app = express();
const cors = require("cors");
const PORT = process.env.PORT || 5001;
// Routes
const imageRoute = require('./Routes/image');
app.use(express.json());
app.use(cors());
require('dotenv').config()
require('./db.config');
app.use('/image',imageRoute);
app.get('/',(req,res) => {
res.send('First Route!')
})
app.listen(PORT,() => {
console.log(`listening on port ${PORT}`)
})
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
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).