CouchDB Database create/delete - node.js

I have a NodeJS application and I have a problem using nano to create/delete a database. I want to check if there is a database with the users name. If there is a database I would like to clear it so I destroy it and create a new one.
module.exports.createDB = function () {
try {
nano.db.list().then((body) => {
// body is an array
body.forEach((db) => {
if(db == getUser.username){
nano.db.destroy(getUser.username)
}
});
});
nano.db.create(getUser.username).then((body) => {
nano.use(getUser.username).insert(
{ "views":
{ "webview":
{ "map": "function (doc) {\n emit(doc.msg, 1);\n}", "reduce": "_count" }
}
}, '_design/output', function (error, response) {
console.log("Design Created");
});
})
} catch (error) {
console.log(error);
}
}
If there is no database with this name it works fine but if there is a database with the same name i get the error:
(node:33354) UnhandledPromiseRejectionWarning: Error: The database could not be created, the file already exists.
But I don't know why because I destroy this database before?

You can check whether a database exists by calling db.info(). If it exists, you can then destroy it and re-create it. If it doesn't exist, just create it:
const Nano = require('nano')
const nano = Nano(process.env.COUCH_URL)
const main = async () => {
const DBNAME = 'mydb'
const db = nano.db.use(DBNAME)
try {
const info = await db.info()
console.log('DB Exists!', info)
await nano.db.destroy(DBNAME)
} catch (e) {
console.log('DB does not exist!')
}
await nano.db.create(DBNAME)
}
main()

Related

Cannot close and open a new database connection with mongoose

I'm using a lambda function with nodejs and mongoose that uses a client file for connections. I work with two databases, the first is to read data, after this i need close the current connection for open a new, but i have problems and errors with this
I tried adding mongoose.connection.close(), mongoose.disconnect(), overwriting directly the connection
But i get the follow responses:
"mongoclient must be connected to perform this operation"
"can't call 'openuri()' on an active connection with different connection strings"
This is my code
let conn = null;
let mongoURI = '';
class MongoDB {
// execute mongo connection
static initMongo(context) {
if (conn == null) {
mongoLogger.info(context, 'trying_connect_mongo', {});
conn = mongoose.connect(mongoURI, {});
// On db connection
mongoose.connection.on('connected', () => {
mongoLogger.info(context, 'connection_mongo_successful', {});
});
// On db error
mongoose.connection.on('error', (err) => {
mongoLogger.error(context, 'connection_mongo_failed', { err: err });
});
} else {
mongoLogger.info(context, 'connection_mongo_already_exists', {});
}
}
// setUp mongoConnection
static async setUp(context) {
// Get secret from mongo uri
try {
mongoURI = await clientSecrets.getSecret(MONGO_URI);
this.initMongo(context);
} catch (err) {
mongoLogger.error(context, 'get_mongo_uri_secret_failed', { err: err });
}
}
// setUp mongoConnection analytics
static async setUpAnalytics(context) {
// Get secret from mongo uri
try {
mongoURI = await clientSecrets.getSecret(MONGO_ANALYTICS_URI);
this.initMongo(context);
} catch (err) {
mongoLogger.error(context, 'get_mongo_analytics_uri_secret_failed', { err: err });
}
}
// close current connection and open a new specified connection
static async closeConnection(context, type) {
// type 1 insights database
// type 2 anlytics database
try {
await mongoose.connection.close();
conn = null;
if (type === 1) {
await this.setUp(context);
} else if (type === 2) {
await this.setUpAnalytics(context);
}
} catch (err) {
mongoLogger.error(context, 'cancel_current_connection_failed', { err: err });
}
}
}

How to dynamically delete MongoDB entry using API route

I would just like to simply delete a record from a dynamically displayed list. I've tried every permutation of the backend code and ai just can't get it to work.
The backend is called like this:
async function deletePost() {
setLoading(true)
try {
await axios.delete(`/api/delete/${id}`)
alert("Post deleted")
}
catch (err) {
// notify user that something went wrong
console.log(err)
}
finally {
setLoading(false)
}
setLoading(false)
}
And /api/delete/${id} looks like this:
import { connectToDatabase } from "util/mongodb"
export default async (req, res) => {
const { id } = req.query;
console.log(id)
try {
const { db } = await connectToDatabase()
await db.collection("users").deleteOne({'_id': `ObjectId("${id}")`})
res.sendStatus(200).send({ done: true })
}
catch (error) {
return res.json({ error })
}
}
The console log shows the correct post id, the alert in the 'try' frontend code displays, but the dam post just wont delete. Can anyone offer any advice please? I have tried ".deleteOne({'_id': id})" but that does nothing either.
I believe you are searching for a string, instead of the ObjectId, so no documents match.
You can fix it by converting to ObjectId and then using the value converted, .deleteOne.
var ObjectId = require('mongodb').ObjectId;
const { id } = req.query;
const convertedObjectId = new ObjectId(id);
db.collection("users").deleteOne({_id: convertedObjectId })
Actual example from documentation:
try {
db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
print(e);
}
Reference: MongoDB Documentation - Delete One.
Fixed problem:
app.delete("/cars/:id", async (req, res) => {
const carsId = req.params.id;
const query = { _id: ObjectId(carsId) };
const result = await carCollection.deleteOne(query);
res.send(result);
});

Why is my graphql apollo resolver not being called?

I'm pretty new to graphql (and nodejs as well). I'm following a Udemy course on Apollo and mongo which has been going well mostly. However I can't get one of the resolvers to be called. Another resolver is working fine, and they appear to use the same layout. Also, the context is being called before the resolver that is not being called, so I know it's at least getting that far.
Here is the root server.js with the working context:
const resolvers = require('./resolvers');
...
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
await verifyUser(req);
console.log("=== context ran, user email : ", req.email) ;
return {
email: req.email,
loggedInUserId: req.loggedInUserId
}
}
});
resolvers are modularized, and combined in a /resolvers/index.js, here:
const { GraphQLDateTime } = require('graphql-iso-date')
const userResolver = require('./user');
const taskResolver = require('./task');
const customDateScalarResolver = {
Date: GraphQLDateTime
}
module.exports = [
userResolver,
taskResolver,
customDateScalarResolver
]
and here is the tasks resolver, located at /resolvers/task.js, which is the one not being called:
const uuid = require('uuid')
const { combineResolvers } = require('graphql-resolvers');
const { users, tasks } = require('../constants');
const Task = require('../database/models/task');
const User = require('../database/models/user');
const { isAuthenticated, isTaskOwner } = require('./middleware');
module.exports = {
Query: {
tasks: async ( _, __, { loggedInUserId }) => {
console.log("tasks query, loggedInUserId : ", loggedInUserId);
try {
const tasks = await Task.find( { user: loggedInUserId });
return tasks;
} catch (error) {
console.log(error);
throw error;
}
},
task: async ( parent, { id }, ) => {
console.log("taskbyId query, id : ", id);
// tasks.find(task => task.id == args.id);
try {
const task = await Task.findById(id);
console.log("taskById query, found task? : ", task);
return task;
} catch (error) {
console.log(error);
throw error;
}
},
},
Mutation: {
// createTask: combineResolvers(isAuthenticated, async (_, { input }, { email }) => {
createTask: async (_, { input }, { email }) => {
try {
console.log("creating task, email : ", email);
const user = await User.findOne({ email });
const task = new Task({ ...input, user: user.id });
const result = await task.save();
user.tasks.push(result.id);
await user.save();
return result;
} catch (error) {
console.log(error);
throw error;
}
}
// )
},
Task: {
user: async ( parent ) => {
console.log("in task.user field resolver");
try {
const user = await User.findById(parent.user);
return user;
} catch (error) {
console.log(error);
throw error;
}
}
},
}
When I run the tasks query, the console.log from the context setup function logs 3 times, but does NOT log the console.log line from the tasks resolver. It also appears to not return at all. I'm just using the default graphiql web client. The verifyUser() does find a return a user, so I know the db connection is working fine as well.
mergeResolvers should be used to merge resolvers.
It's designed to merge different [entities] object [/structured] resolvers before use [as one tree structured] in server [config].
F.e. it merges/combines respectively [by type] Query resolvers from users resolver with tasks Query resolvers ... and Mutation resolvers from users resolver with tasks Mutation resolvers.

Serverless: dynamodb giving error on create record when trying with async/await

I am trying to create a record in dynamodb(Using dynamoose). code is
class Test {
constructor() {
this.table = dynamoose.model(tableName, tableSchema);
}
// userdata object - {
// cusotmerEmail: 'tushar.gaurav+testf40#accionlabs.com',
// customerBusinessName: 'DoogleDnd',
// customerFirstName: 'Tushar',
// customerId: 101211,
// customerLastName: 'Gaurav',
// isDeleted: false,
// sku: '100',
// userId: '5c1776e94bea867c3f896236'
// }
async createUser(userData) {
try {
const res = await this.table.create(userData);
console.log('Update user record - ', res);
return res;
} catch (error) {
throw new Error(error);
}
}
}
*input values to the create function are correct as the same input I tried with batchPut(), it's working.
And even update call to the table is also working.
async updateUser(userData) {
try {
const res = await this.table.update(userData);
console.log('Updated user record - ', res);
return res;
} catch (error) {
throw new Error(error);
}
}
This is the error I am getting -
Error - {"message":"The conditional request failed", "code":"ConditionalCheckFailedException", "statusCode":400}
This is the calling function -
module.exports.subscribeUser = async (event) => {
let inputBody = (typeof event.body === 'object' ? event.body :
JSON.parse(event.body));
inputBody.userId = event.pathParameters.id;
try {
// Validate input
await asisvc.validateInput(inputBody);
inputBody = await UserSvc.constructUserObject(inputBody);
console.log('Constructed object - ', JSON.stringify(inputBody));
const userData = await testObj.createUser(inputBody);
return Utils.buildResp(codes.ok, { userData }, {});
} catch (error) {
console.log(error);
return Utils.buildResp(codes.badrequest, { Error:
Utils.getErrString(error) }, {});
}
};
I tried googling it, but didn't find any proper document.
Thanks in advance.
In Dynamoose by default we check to see if the primary key already exists in the table when using the Model.create method.
So your error:
{"message":"The conditional request failed", "code":"ConditionalCheckFailedException", "statusCode":400}
Indicates that the primary key already exists in the table. So you are trying to create a duplicate item.
In the documentation there is an options property that you can use to allow overriding the object.
For example the following code will allow overrides:
const res = await this.table.create(userData, {overwrite: true});

MongoDB in NodeJS Class Structure

Is there a way to use MongoDB in a class structure in NodeJS?
I understand you can do CRUD operations on the DB within the connection method like
mongo.connect(url, function(err, client){//do some CRUD operation});
but I was wondering if there was a way to open the connection to the DB, have access to it across the class, then close it when you are done working with the class.
For example:
class MyClass {
constructor(databaseURL) {
this.url = databaseURL;
}
async init() {
//make connection to database
}
async complete_TaskA_onDB() {
//...
}
async complete_TaskB_onDB() {
//...
}
async close_connection() {
//close connection to database
}
}
Edit:
I just came across more information in the Node.JS Mongo docs. Maybe something along the lines of this would work?
//constructor()
this.db = new MongoClient(new Server(dbHost, dbPort));
//init()
this.db.open();
//taskA()
this.db.collection(...).update(...);
//close_connection()
this.db.close();
You can create a class of which will act as a wrapper on any core lib, doing so will give you below advantages:
Wrapping any core module with your own service will allow you to:
Create a reusable service that you could use on multiple components in your app.
Normalize the module's API, and add more methods your app needs and the module doesn’t provide.
Easily replace the DB module you chose with another one (if needed).
I have created that service which I use it in my projects for MongoDB:
var mongoClient = require("mongodb").MongoClient,
db;
function isObject(obj) {
return Object.keys(obj).length > 0 && obj.constructor === Object;
}
class mongoDbClient {
async connect(conn, onSuccess, onFailure){
try {
var connection = await mongoClient.connect(conn.url, { useNewUrlParser: true });
this.db = connection.db(conn.dbName);
logger.info("MongoClient Connection successfull.");
onSuccess();
}
catch(ex) {
logger.error("Error caught,", ex);
onFailure(ex);
}
}
async getNextSequence(coll) {
return await this.db.collection("counters").findOneAndUpdate({
_id: coll
},
{$inc: {seq: 1}},
{projections: {seq: 1},
upsert: true,
returnOriginal: false
}
);
}
async insertDocumentWithIndex(coll, doc) {
try {
if(!isObject(doc)){
throw Error("mongoClient.insertDocumentWithIndex: document is not an object");
return;
}
var index = await this.getNextSequence(coll);
doc.idx = index.value.seq;
return await this.db.collection(coll).insertOne(doc);
}
catch(e) {
logger.error("mongoClient.insertDocumentWithIndex: Error caught,", e);
return Promise.reject(e);
}
}
async findDocFieldsByFilter(coll, query, projection, lmt) {
if(!query){
throw Error("mongoClient.findDocFieldsByFilter: query is not an object");
}
return await this.db.collection(coll).find(query, {
projection: projection || {},
limit: lmt || 0
}).toArray();
}
async findDocByAggregation(coll, query) {
if(!query.length){
throw Error("mongoClient.findDocByAggregation: query is not an object");
}
return this.db.collection(coll).aggregate(query).toArray();
}
async getDocumentCountByQuery(coll, query) {
return this.db.collection(coll).estimatedDocumentCount(query || {})
}
async findOneAndUpdate(coll, query, values, option) {
if(!(isObject(values) && isObject(query))){
throw Error("mongoClient.UpdateDocument: values and query should be an object");
}
return this.db.collection(coll).findOneAndUpdate(query, {$set : values}, option || {})
}
async modifyOneDocument(coll, query, values, option) {
if(!(isObject(values) && isObject(query))){
throw Error("mongoClient.ModifyOneDocument: values, query and option should be an object");
}
return await this.db.collection(coll).updateOne(query, values, option || {})
}
async close() {
return await this.db.close();
}
}
module.exports = {
mongoDbClient: mongoDbClient
}
For my complete lib access you can refer here
Yes, you can do all of this inside a class, but you cannot set a member variable like db after the constructor has been set. You can make it a global variable, but you cannot set the variable.
const MongoClient = require('mongodb').MongoClient;
var database; //global
class DB {
constructor(url, dbName) {
this.url = url;
this.dbName = dbName;
}
connect() {
console.log('connecting to database ' + this.dbName + ' with URL ' + this.url);
return new Promise((resolve, reject) => {
MongoClient.connect(this.url, (err, client) => {
if (err) {
reject(err);
} else {
database = client.db(this.dbName);
resolve(client.db(this.dbName));
}
});
})
}
}

Resources