In trying to build my first express API, I am encountering many problems. I am following some simple guide on youtube, and his code works (FOR HIM). When I try it with Postman, I simply get nothing, but it appears to be in some kind of loop (because I handle the errors)
I have checked that my route is ok, and tried experimenting with next() (which seems like I don't need it just yet)
Player is my model made with Mongoose
app.get("/players/:id", (req, res) => {
const id = req.params.id;
Player.findById(id)
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json(doc);
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
So when trying a GET in Postman on:
http://localhost:3000/players/5cf66338f00c424494316eb2
I get a loading screen, and after some time "There was an error connecting to...".
Any help/tips/solution/insights are appreciated!
If your repo is up-to-date, then you are not connecting your app with your database.
Add the following code in your app replacing the database with your own database:
mongoose.connect('mongodb://localhost:27017/database', {useNewUrlParser: true});
Related
I am kind of stuck at something, I am working on a personal blog that is full stack using mongodb with node.js and express. In that blog website only one user can sign up, and all posts are connected to that user. I am using the REST API to create a controller that deletes a user along with all the posts. I have the User and the Post object available and I was wondering if there is a way where I can use the User and Post schema objects to delete the user and ALL posts. I dont want to use the db.collection('posts') thing because I havent used that anywhere else. I went through mongodb node.js driver docs and I still cant figure out how to do it.
exports.deleteUser = (req, res, next) => {
User.find().then(user => {
//what do i do here?
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// you need to do next() otherwise error will not reach
// our middlewear in app.js file
next(err);
})
Post.find().then(allPosts => {
if (!allPosts) {
//what do i do here?
}
res.status(200).json({message: message})
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// you need to do next() otherwise error will not reach
// our middlewear in app.js file
next(err);
})
}
I would recommend using deleteOne and deleteMany directly instead of using find.
So I'm new to AWS serverless architecture. I deployed my first lambda function using Claudia. I'm not sure whether I did it correctly. I deployed all the APIs to one lambda function using Claudia. The API endpoints works individually when I test it on Insomnia. But when I use it in my application only one specific API works and the lambda dies. For instance, I used this POST request to post some items and I have a useEffect in my React application which has a get request to retrieve all the items from the database. But once I post the item, nothing is returned. Could anyone help me understand what I'm doing wrong. P.S this is my final year project which is due in a few weeks. So, a quick answer would be appreciated.
Here is a sample code.
// Create a new Intake
router.post("/create", async (req, res) => {
const intake = req.body;
const { name, intakeCode, intakeYear } = req.body;
const checkIntake = await Intakes.findOne({
where: {
intakeCode: intakeCode,
},
});
if (checkIntake) {
res.json({ err: `An intake under ${intakeCode} already exists!` });
} else {
try {
await Intakes.create(intake);
res.json({ msg: `Successfully created ${name} ` });
} catch (e) {
if (e.name == "SequelizeDatabaseError") {
res.json({ err: "Year only accepts integer" });
} else {
res.json({ err: e.name });
}
}
}
});
// Find all Intakes
router.get("/findAll", async (req, res) => {
const listOfIntakes = await Intakes.findAll();
res.json(listOfIntakes);
});
Cheers
Looks like you are trying to build a Lambda function using JavaScript - but have encountered problems. I'm not familiar with Claudia. One suggestion that I have is to follow the official AWS SDK for JavaScript DEV Guide here:
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html
That content will walk you through how to create a Lambda function using JS.
I've created a puppy database using My SQL workbench, I am not developing multiples routers that allow me to view all puppies, add a puppy, update a puppy etc. I am currently working on the router to delete a puppy. However, I keep getting a 'ReferenceError: auth is not defined' error.
Here is my code for the router.delete:
try {
const puppyID = req.params.id;
const token = await auth.verify('puppy.remove', req);
await puppyCtrl.removePuppy(puppyID, token.id);
res.json({ message: 'Puppy Removed Successfully' });
} catch (err) {
console.log(err);
res.json({ message: "Failed to delete puppy" });
}
});
I am testing it on Postman and get the "Failed to delete puppy" error on postman. So it does get to the catch. However, I think there is probably an error within my try statement.
I have a rest API and an app that uses it. The app and postman can both make get requests perfectly. The problem is that on delete requests the app does not work Most of the time but postman works every time. The app also always receives an OK if it works or not. Any help would be appreciated. I am using Node.js and MongoDB for the api and Xamarin for the app
Delete code on server:
// Delete a fish with the specified fishId in the request
exports.delete = (req, res) => {
console.log("Atempting to delete fish with id: " + req.params.fishId)
Fish.findByIdAndRemove(req.params.fishId)
.then(fish => {
if (!fish) {
return res.status(404).send({
message: "Fish not found with id " + req.params.fishId
});
}
if (!Fish.findByID(req.params.fishId)) {
return res.status(200).send({
message: "Fish deleted sucsessfully"
});
}
return res.status(500).send({
message: "Could not delete fish with id " + req.params.fishId
});
}).catch(err => {
if (err.kind === 'ObjectId' || err.name === 'NotFound') {
return res.status(404).send({
message: "Fish not found with id " + req.params.fishId
});
}
return res.status(500).send({
message: "Could not delete fish with id " + req.params.fishId
});
});
};
Just wondering why is this with no callback/.then?
if (!Fish.findByID(req.params.fishId)) {
return res.status(200).send({
message: "Fish deleted sucsessfully"
});
}
Isn't findByID async just like findOneAndRemove?
findByID is async yes, you should handle it that way, or maybe a solution could be to check with ObjectID.isValid() before? Then check for the resolved document would be just enough.
I sent a request from postman in nodejs and as a beginner in nodejs i find it hard to debug .Can someone throw light on this ?
Here is the entire repository at this point of time .
https://github.com/kolaveridi/socialnetwork
router.get('/handle/:handle', (req, res) => {
console.log('working');
console.log(req.params.handle);
const errors = {};
Profile.findOne({ handle: req.params.handle })
.populate('user', ['name', 'avatar'])
.then(profile => {
if (!profile) {
errors.noprofile = 'There is no profile for this user';
console.log('no profile');
res.status(404).json(errors);
}
res.json(profile);
})
.catch(err => res.status(404).json(err));
});
I don't see any of the console working on sending this request
when i already have a user with handle 'mom' regsitered ,loggedin .
http://localhost:5000/api/profile/handle/:mom
The problem is not in the source code itself, but in the api url you use to test the app. ":" is only needed in the "handle" route declaration, but in the url you need to skip it:
http://localhost:5000/api/profile/handle/mom
Regarding the question: you can use console.log and build in debugger (node inspect server.js), or you can use IDE debugger.