Module Error and the program not running (mongo documentation) - mongodb

const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb+srv://rohailmalik:<password>#cluster0.1aaikod.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
await client.connect();
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
///Error: Cannot find module '/Users/malikrohail/waitlist/demo.js'
///Error: Cannot find module '/Users/malikrohail/waitlist/demo.js'
please look into this
please look into this

Related

How to run script in mongoDb during the cypress test

I'm trying to run script in mongodb at the beginning of cypress test. I've added method in plugins/index.js to connect to mongo but I'm not sure what to do next. I've try to add in taks db.command with script, but it doesn't work. Any ideas, how I can do this ?
const { MongoClient } = require('mongodb')
const uri = "someUri"
if (!uri) {
throw new Error('Missing MONGO_URI')
}
const client = new MongoClient(uri)
async function connect() {
await client.connect()
return client.db()
}
module.exports = async (on, config) => {
const db = await connect()
on('task', {
};
I found solution to this if anybody will have same problem.
on('task', {
async updateCarColor() {
await db.collection('collectionName').updateOne({"Id": "45"},
{
"$set": {"car.color": "red"}
})
return null
},
})

detecting error for Nextjs API route with Axios

I am using nextjs api/routes
I have a login and when an issue occurs return a 401 and message text that I would like to show to users.
A minimal example is:
Api : /api/v1/auth/sigin.js
export default async (req, res) => {
const { name, password } = req.body;
const url = process.env.SH_API_BASEURL + 'auth/signin';
console.log(url);
try {
const resp = await axios.patch(url, { name, password });
return res.status(200).send(resp.data);
} catch (err) {
const { response } = err;
const status = response.status;
const message = response.data.errors[0].message;
console.log(`status: ${status}, message ${message}`);
return res.status(status).send(message);
}
};
Pages /pages/auth/signin.js
const handleFormSubmit = async (formData, e) => {
e.preventDefault();
try {
const res = await axios.post('/api/v1/auth/signin', formData);
router.push('/secure/home');
} catch (err) {
console.log('pages auth in error');
console.log(err);
setSubmitError(true);
console.log('sigin handle submit error');
}
};
console.log(err) shows the output
Error: Request failed with status code 401
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
How do I get access to the statusCode and text in pages code?
Could any answers be in the context of nextjs api/routes
Thanks
You can access the response property of the axios error to get the status
const handleFormSubmit = async (formData, e) => {
e.preventDefault();
try {
const res = await axios.post('/api/v1/auth/signin', formData);
router.push('/secure/home');
} catch (err) {
console.log(err.response.status);
}
};

mongodb insertOne inside a loop

I want to insert different collections inside a loop.
I already wrote this and it works once.
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
let insertflowers = async (collectionname,query) => {
try {
await client.connect();
const database = client.db('flowers');
const collection = database.collection(collectionname);
return await collection.insertOne(query);
} finally {
await client.close();
}
}
insertflowers('alocasias',{name:'...'}).catch(console.dir);
What I want to do is put it inside a loop like this.
arrayofflowers.forEach( val => {
let flowerType = ...
insertflowers(flowerType,{name:'...'}).catch(console.dir);
});
But I get the following error
MongoError: Topology is closed, please connect
Thank you for reading
In short remove await client.close();
Check https://docs.mongodb.com/drivers/node/usage-examples/insertMany/ to insert bulk records at once.
You're in race condition so when insertflowers process is running in parallel connection is closed and opening.
So when you try to insert data connection is closed by another call to insertflowers.
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
let connection;
const connect = async () => {
if (!connection) { // return connection if already connected
connection = await client.connect();
}
return connection;
});
let insertflowers = async (collectionname,query) => {
try {
const conn = await connect();
const database = conn.db('flowers');
const collection = database.collection(collectionname);
return await collection.insertOne(query);
} finally {
console.log('insertflowers completed');
// await client.close(); remove this
}
}
Another option - Not a good idea though
Make insertflowers is run the sync.

Connect Apollo with mongodb

I want to connect my Apollo server with my mongoDB. I know there are many examples out there, but I get stuck at the async part and did not found a solution or example for that (that's strange, am I completly wrong?)
I started with the example from next.js https://github.com/zeit/next.js/tree/master/examples/api-routes-apollo-server-and-client .
But the mongodb integration is missing.
My code
pages/api/graphql.js
import {ApolloServer} from 'apollo-server-micro';
import {schema} from '../../apollo/schema';
const apolloServer = new ApolloServer({schema});
export const config = {
api: {
bodyParser: false
}
};
export default apolloServer.createHandler({path: '/api/graphql'});
apollo/schema.js
import {makeExecutableSchema} from 'graphql-tools';
import {typeDefs} from './type-defs';
import {resolvers} from './resolvers';
export const schema = makeExecutableSchema({
typeDefs,
resolvers
});
apollo/resolvers.js
const Items = require('./connector').Items;
export const resolvers = {
Query: {
item: async (_parent, args) => {
const {id} = args;
const item = await Items.findOne(objectId(id));
return item;
},
...
}
}
apollo/connector.js
require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;
const password = process.env.MONGO_PASSWORD;
const username = process.env.MONGO_USER;
const uri = `mongodb+srv://${username}:${password}#example.com`;
const client = await MongoClient.connect(uri);
const db = await client.db('databaseName')
const Items = db.collection('items')
module.exports = {Items}
So the problem is the await in connector.js. I have no idea how to call this in an async function or how to provide the MongoClient on an other way to the resolver. If I just remove the await, it returns – obviously – an pending promise and can't call the function .db('databaseName') on it.
Unfortunately, we're still a ways off from having top-level await.
You can delay running the rest of your code until the Promise resolves by putting it inside the then callback of the Promise.
async function getDb () {
const client = await MongoClient.connect(uri)
return client.db('databaseName')
}
getDb()
.then(db => {
const apollo = new ApolloServer({
schema,
context: { db },
})
apollo.listen()
})
.catch(e => {
// handle any errors
})
Alternatively, you can create your connection the first time you need it and just cache it:
let db
const apollo = new ApolloServer({
schema,
context: async () => {
if (!db) {
try {
const client = await MongoClient.connect(uri)
db = await client.db('databaseName')
catch (e) {
// handle any errors
}
}
return { db }
},
})
apollo.listen()

Why is Mongo Dart not surfacing errors?

I'm trying to use Dart's aync programming with mongo model
I'm looking at the source for DbCollection and it appears the DbCollection.find() returns a Stream
https://github.com/vadimtsushko/mongo_dart/blob/master/lib/src/database/dbcollection.dart
I want to turn a response into a List of Maps so im doing the following:
try {
finder = await collection.find(query);
} catch(e) {
print(e);
}
try {
list = await finder.toList();
} catch(e) {
print(e);
}
Problem:
1. Execution bombs out out collection.find
2. No error is trapped
Question: Is there a different approach to working with this api the i need to be using?
Take a look at package readme. There are some examples.
Something like this should do:
var collection = db.collection('user');
await collection.find(where.lt("age", 18)).toList();
But actually even with superfluos await it should work too.
I've made a simple example with your snippet and it work for me as is
import 'package:mongo_dart/mongo_dart.dart';
main() async {
Db db = new Db('mongodb://127.0.0.1:27017/mongo_dart-test','sample_test');
DbCollection newColl;
await db.open();
newColl = db.collection("new_collecion");
await newColl.remove();
await newColl.insertAll([{"a":1}]);
var finder;
try {
finder = await newColl.find();
} catch(e) {
print(e);
}
List list;
try {
list = await finder.toList();
} catch(e) {
print(e);
}
print(list);
await db.close();
}