Reputation:
I have a MongoDB API return in node js.
In the database I have values but I can't retrieve it with the API.
My model
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true)
const plannerSchema = mongoose.Schema({
email: {
type: String,
required: true
},
task: {
type: String,
required: true
},
createdat: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('planner', plannerSchema);
My code
const express = require('express');
const router = express.Router();
const PlannerSchema = require('../models/planner');
router.post('/get', async(req, res) => {
let email = req.body.email
try {
const tasks = PlannerSchema.find({email:email})
if(tasks){
res.status(200).json({
message:"success",
content:tasks
})
} else {
res.status(200).send('empty')
}
} catch (error) {
res.status(400).send('error-occurred')
}
})
I always get the response as error-occurred.
Please give me a solution
Thanks in advace
Upvotes: 0
Views: 252
Reputation: 854
You can also use then() instead of await like below:
const express = require('express');
const router = express.Router();
const PlannerSchema = require('../models/planner');
router.post('/get', async(req, res) => {
let email = req.body.email
try {
const tasks = PlannerSchema.find({email:email}).then((doc)={
if(doc){
res.status(200).json({
message:"success",
content:tasks
})
} else {
res.status(200).send('empty')
}
});
} catch (error) {
res.status(400).send('error-occurred')
}
})
Upvotes: 0
Reputation: 963
PlannerSchema.find({email:email})
is asynchronous so use await
keyword. And find
method is deprecated in MongoDB so better to use findOne
. As per the ES6 version if key and value are the same then you can use the only email
instead of email:email
. So your code finally will be
const express = require('express');
const router = express.Router();
const PlannerSchema = require('../models/planner');
router.post('/get', async (req, res) => {
let email = req.body.email;
try {
//changes here
const tasks = await PlannerSchema.findOne({email})
if (tasks) {
res.status(200).json({
message: "success",
content: tasks
});
} else {
res.status(200).send('empty');
}
} catch (error) {
console.log(error); //to print error on terminal
res.status(400).send('error-occurred');
}
})
Upvotes: 1
Reputation: 26
const express = require('express');
const router = express.Router();
const PlannerSchema = require('../models/planner');
router.post('/get', async (req, res) => {
let email = req.body.email;
try {
const tasks = await PlannerSchema.find({
email: email
}) // use await here
if (tasks) {
res.status(200).json({
message: "success",
content: tasks
});
} else {
res.status(200).send('empty');
}
} catch (error) {
console.log(error); //to print error on terminal
res.status(400).send('error-occurred');
}
})
Upvotes: 0