asyncData get profile from db - mongodb

So i want to fetch from db using asyncdata and axios, Here's the code, The problem is that no request is sent, And i'm wondering if someone can help me catch the error.
async asyncData({ $axios, store }) {
try {
let profile = await $axios.$get('/profile', store.state.auth.id)
return { profile }
} catch (error) {
console.log(error.message)
}
},
router.get('/profile', async (req, res) => {
const { userId } = req.body
try {
const profileUser = await User.findById(userId)
res.send(profileUser)
} catch (e) {
console.log(e)
res.status(400).json(e.message)
}
})

You may need to modify your route to the following, if you want to pass the id as parameter
router.get('/profile/:id', async (req, res) => {
const { userId } = req.params.id;
try {
const profileUser = await User.findById(userId)
res.send(profileUser)
} catch (e) {
console.log(e)
res.status(400).json(e.message)
}
})
and add profile id as route parameter
async asyncData({ $axios, store }) {
try {
let profile = await $axios.get('/profile/{profile_id_here}')
return { profile }
} catch (error) {
console.log(error.message)
}
}
Otherwise, if you want to get the id of the authenticated user (may be resolved from a Bearer token), it needs to be set to the request object in you authentication middleware.
In your authentication middleware,
const user = await _authService.validateFromToken(bearerToken);
if (user) {
req.user = user;
}
then you can access authenticated user as,
router.get('/profile', async (req, res) => {
const { userId } = req.user._id;
try {
const profileUser = await User.findById(userId)
res.send(profileUser)
} catch (e) {
console.log(e)
res.status(400).json(e.message)
}
})

Related

How to find email in MongoDB using NextJS and mongoose

I am trying to create a login endpoint that checks to see if an email is already stored in the database. If an email exists it will return an error, otherwise it notifies that an email exists. For some reason, User.findOne({ email: req.body.email }) does not seem to work. Here is the code I am currently using (located in pages/api/login.ts.)
import dbConnect from "../../lib/dbConnect";
import User from "../../models/User"
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await dbConnect()
//type of request
const {method} = req
if (method === "POST") {
try {
await User.findOne({email: req.body.email}, function(err, user) {
if (err) {
res.status(400).json({error: "no email found"})
}
if (user) {
res.status(200).json({success: "email found", data: user})
}
})
} catch (error) {
res.status(400).json({error: "connection error"})
}
}
}
I never seen callback with await syntax:
try {
const user = await User.findOne({ email: req.body.email });
if (user) {
res.status(200).json({success: "email found", data: user})
}
} catch (error) {
// handle error here
}

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);
}
};

How to merge two schemas in mongodb

I have a post schema and user schema and I want to merge them together. I waant to know how to do it. So far I have this code but I keep returning promises. When I add then after the .map, I get no result. Any help would be appreciated
let posts = await Post.find();
console.log(posts);
let test = await posts.map(async(post) => {
const creator = await User.findOne({token: post.creator});
var username = null;
if(creator){
username = creator.username;
}
return {...post._doc, username: username};
});
return posts;
you can use q and async module
const q = require("q");
const async = require("async");
async function mainFunction() {
try {
let posts = await Post.find();
let result = await getUser(posts);
console.log(result)
} catch (error) {
console.error(error);
return { error: error };
}
}
async function getUser (posts) {
let defer = q.defer;
let test = [];
async.eachSeries(posts,async (post) => {// like loop
try {
let creator = await User.findOne({ token: post.creator });
var username = null;
if (creator) {
username = creator.username;
}
test.push({ ...post._doc, username: username });
} catch (error) {
console.log(error);
}
},() => {//callback
console.log("finish loop");
defer.resolve(test); // when finished loop return result
}
);
return defer.promise;
};

"No current user" from currentSession() AWS Amplify and Cognito

I am trying to get a REST API to return currentSession() from AWS Amplify and Cognito. The SignIn function works and i get a CognitoUser object returned, however, the getSession() function returns "No current user"
const Amplify = require('aws-amplify');
const express = require('express');
const router = express.Router();
Amplify.default.configure({
Auth: {
region: 'REGION',
userPoolId: 'USERPOOLID',
userPoolWebClientId: 'WEBCLIENTID',
authenticationFlowType: 'AUTHTYPE',
}
})
router.post('/', (req, res) => {
async function signIn(username, password) {
try {
Amplify.Auth.signIn(username, password)
.then(() => getSession())
.catch(err => console.log(err));
} catch (error) {
res.json(error);
}
}
async function getSession() {
try {
Amplify.Auth.currentSession()
.then(data => console.log(data))
.catch(err => console.log(err));
} catch (error) {
res.json('error');
}
}
signIn(req.body.u, req.body.p);
});
Help!

MongoDB issue with saving value returned from findByID

I have an issue with function which update password. What I would like to have is a function which will update logged user data.
export const updateMe = async (req, res, next) => {
if (!req) {
res.status(400).end()
}
try {
const updatedDoc = await User.findById(req.user._id, function(err, doc) {
if (err) return next(err)
doc.password = req.body.password
doc.save()
})
.lean()
.exec()
res.status(200).json({ data: updatedDoc })
} catch (e) {
console.log(e)
res.status(400).end()
}
}
I have written middleware which will hash password before it will be saved.
userSchema.pre('save', function(next) {
if (!this.isModified('password')) {
return next()
}
bcrypt.hash(this.password, 8, (err, hash) => {
if (err) {
return next(err)
}
this.password = hash
next()
})
})
I do not know why error is always reciving with message "doc.save() is not a funcition"
You are mixing promise and await code, also doc.save() returns a promise so you need to await it.
( I assume you are already setting req.user._id in a middleware, and it is not null.)
So your method must be like this if async/await is used:
export const updateMe = async (req, res, next) => {
if (!req.body.password) {
return res.status(400).send("Password is required");
}
try {
let updatedDoc = await User.findById(req.user._id);
updatedDoc.password = req.body.password;
updatedDoc = await updatedDoc.save();
res.status(200).json({ data: updatedDoc });
} catch (e) {
console.log(e);
res.status(400);
}
};