Endpoint Not Responding - mongodb

I'm trying to make CRUD app using mongodb atlas and express when i need to make an GET endpoint its not responding and keeps loading here the code
Get Endpoint:
app.get('/getTodo',(req, res) => {
const cursor = db.getDB().collection(coll).find({});
cursor.toArray(( todos) => {
res.send(todos);
});
}
});
I tried to catch the error using try catch there was no error then i tried to log something after it it logged. I also tried to user async and await samething nothing changed.
what should I do?? what I'm doing wrong??

Related

Insert a user by default in MongoDB in Nest JS (Only when the app starts)

I am changing the project from expressjs to nestjs.
In express, I added an admin user to the database by default in app.ts.
like this:
public async addDefaultAdmin() {
UserModel.find({ role: Roles.admin }).then(async (superAdmin) => {
if (superAdmin.length === 0) {
try {
const newUser = new UserModel({...});
await this.hashPassWord(newUser);
await newUser.save();
console.log("default admin successfully added.");
} catch (error: any) {
console.log(error);
}
}
});
}
I wanted to know how I can do this in NestJS?
Does NestJS or typeOrm have a solution for this issue?
You may need to use lifecycle events. NestJS fires events during application bootstrapping and shutdown.
According to doc, onApplicationBootstrap() event may be helpful in your case.
Called once all modules have been initialized, but before listening for connections.
However, NestJS does not expose a hook after the application starts listening, so in this case you need to run your custom function inside of bootstrap function right after the server could listen to a port.
The pseudocode would be like this:
// main.ts
import { User } from '/path/to/user.entity';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
...
await app.listen(3000);
let user = app.get(getRepositoryToken(User)); // You need to pass the entity file to typeorm
await addDefaultAdmin(user); // Pass the user model, and call the function
}
bootstrap();

Mongoose save method seems to not be working

I am trying to create a REST API. I am pretty new to the back end and am just practicing on my own for the time being. For my code, I know it's bad practice to store the plain text password but again, this is completely for practice and will never go live. I will also add encryption at a later point for practice.
My issue is I am not sure why my API does not work. I see where it fails, it fails in the catch block when I try to save a user but I do not get any error to tell me what is wrong exactly, besides the once I force. I have another part on this website that follows almost the exact same logic and it works perfectly but for this one it does not. I have no idea how to solve my issue but after googling I still cannot figure it out. It looks perfectly fine too me, but as mentioned I am pretty new to the backend.
This is my controller function:
const signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(new HttpError('Invalid inputs passed, please check your data', 422));
}
const { name, email, password, places } = req.body;
let existingUser;
try {
existingUser = await User.findOne({email: email}) // finds one document matching our criteria we set
} catch(err) {
const error = new HttpError('Signing up failed, please try again later', 500);
return next(error);
}
if (existingUser) {
const error = new HttpError('User exists already, please login instead', 422);
return next(error);
}
const createdUser = new User({
name,
email,
image: 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260',
password,
places
});
try {
await createdUser.save();
} catch(err) {
const error = new HttpError(
'Signing up failed', 500
);
return next(error);
}
res.status(201).json({user: createdUser.toObject({ getters:true })});
};
I use Postman to send the request to my API endpoint with all of the correct information. Based on what I recieve back it is failing in the try catch block of await createdUser.save()
For anyone who finds this from google this was my solution:
First I suggest you add this into your save method to try and diagnose the problem
await createdUser.save(function(err){
if(err){
console.log(err);
return;
}
});
This help me greatly as it gave me more information on how to solve it.It turns out my problem was because I misspelled a field in my Schema. So extremely simple solution!

AWS Cognito deleteUser in flutter not working

I am trying to implement deleteUser function in cognito which allows the user to delete their own account information by using this code
void deleteUser() async {
try {
await Amplify.Auth.deleteUser();
final state = AuthState(authFlowStatus: AuthFlowStatus.none);
authStateController.add(state);
print('Delete user succeeded');
} on AmplifyException catch (e) {
print('Delete user failed with error: $e');
}
}
However, this code of course is not working for some reason and I don't know why. I also have the user's database in Amplify datastore graphql so I tried deleting the user's datastore data first before getting rid of the user's congnito data but it still does not work. This is the code that I am using to delete user's data from datastore. Please help me out by telling me how I can delete a user's cognito and datastore data.
void deleteUser (DeleteUserData data) async {
(await Amplify.DataStore.query(User.classType, where: User.EMAIL.eq(data.email)))
.forEach((element) async {
try {
await Amplify.DataStore.delete(element);
print('Deleted a user');
} on DataStoreException catch (e) {
print('Delete failed: $e');
}
});
}
Please help me out.
I was facing the same problem, I took a look into the insides of deleteUser method in the AWS api, something I strongly recommend, and I discovered that this API is only available in iOS.
screenshot
I was using amplify_auth_cognito: 0.4.5 and amplify_flutter: 0.4.5.
Upgraded the libraries to 0.5.1 and the warning has disappeared, maybe you can try using a different version of yours (I'm not using Amplify, just simple Cognito).
Cheers.

How can I catch errors in my firebase function when setting a document fails?

I have a firebase cloud function to create a user document with user data whenever a user registers. How would I return an error when the set() fails? Since this is not an http request (an I don't want to use an http request in this case) I have no response. So how would I catch errors?
export const onUserCreated = functions.region('europe-west1').auth.user().onCreate(async user => {
const privateUserData = {
phoneNumber: user.phoneNumber
}
const publicUserData = {
name: 'Nameless'
}
try
{
await firestore.doc('users').collection('private').doc('data').set(privateUserData);
}catch(error)
{
//What do I put here?
}
try
{
await firestore.doc('users').collection('public').doc('data').set(publicUserData);
}catch(error)
{
//What do I put here?
}
});
You can't "return" an error, since the client doesn't even "know" about this function running, there is nobody to respond to.
You can make a registration collection, and in your function make a document there for the current user (using the uid as the document id). In that document, you can put any information you'd like your user to know (status, errors, etc).
So your clients would have to add a listener to this document to learn about their registration.
In your particular code, I think the error is in doc('users'). I guess you meant doc('users/'+user.uid).
Your catch -block will receive errors that occur on your set -call:
try {
await firestore.doc('users').collection('public').doc('data').set(publicUserData);
} catch (error) {
// here you have the error info.
}

Error handling with Mongoose

I am an absolute NodeJS beginner and want to create a simple REST-Webservice with Express and Mongoose.
Whats the best practice to handle errors of Mongoose in one central place?
When anywhere an database error occurs I want to return a Http-500-Error-Page with an error message:
if(error) {
res.writeHead(500, {'Content-Type': 'application/json'});
res.write('{error: "' + error + '"}');
res.end();
}
In the old tutorial http://blog-next-stage.learnboost.com/mongoose/ I read about an global error listener:
Mongoose.addListener('error',function(errObj,scope_of_error));
But this doesn't seem to work and I cannot find something in the official Mongoose documentation about this listener. Have I check for errors after every Mongo request?
If you're using Express, errors are typically handled either directly in your route or within an api built on top of mongoose, forwarding the error along to next.
app.get('/tickets', function (req, res, next) {
PlaneTickets.find({}, function (err, tickets) {
if (err) return next(err);
// or if no tickets are found maybe
if (0 === tickets.length) return next(new NotFoundError));
...
})
})
The NotFoundError could be sniffed in your error handler middleware to provide customized messaging.
Some abstraction is possible but you'll still require access to the next method in order to pass the error down the route chain.
PlaneTickets.search(term, next, function (tickets) {
// i don't like this b/c it hides whats going on and changes the (err, result) callback convention of node
})
As for centrally handling mongoose errors, theres not really one place to handle em all. Errors can be handled at several different levels:
connection errors are emitted on the connection your models are using, so
mongoose.connect(..);
mongoose.connection.on('error', handler);
// or if using separate connections
var conn = mongoose.createConnection(..);
conn.on('error', handler);
For typical queries/updates/removes the error is passed to your callback.
PlaneTickets.find({..}, function (err, tickets) {
if (err) ...
If you don't pass a callback the error is emitted on the Model if you are listening for it:
PlaneTickets.on('error', handler); // note the loss of access to the `next` method from the request!
ticket.save(); // no callback passed
If you do not pass a callback and are not listening to errors at the model level they will be emitted on the models connection.
The key take-away here is that you want access to next somehow to pass the error along.
hey this is the simplest way i found..
try { } catch (error) {
console.log(error);
// checking validation
if (error.name === "ValidationError") {
const message = Object.values(error.errors).map(value => value.message);
return res.status(400).json({
error: message
})
}
res.status(400).json(error.message)
}
}
just copy paste