I want to get my data with 2 function.
for get by collectionid.
function for getbytitle.
How can I make it ? In normally i getting my datas like :
router.get("/:collectionId", async (req, res) => {
try {
const post = await Article.findOne({ collectionid: req.params.collectionId}).populate('author').then(x=>{
res.json(x)
})
} catch (err) {
console.log(err);
}
});
But with that function i can only get with collectionid. How can i make for both ?
Thanks for replies!
You can have serverale in find like that:
.findOne({ collectionid: req.params.collectionId, title: titleyouwant })
See here: Mongoose - multiple parameters in findOne
There is a mistake your are doing in this. Don't use async/await and then/catch together. You can do something like this:
router.get("/:collectionId", async (req, res) => {
try {
const post = await Article.findOne({ collectionid: req.params.collectionId}).populate('author');
console.log(post)
} catch (err) {
console.log(err);
}
});
If you need a query for getbytitle in the same route, I cam add it.
Related
I want to use regex such that in the url /todos?q=dho gives me all the results regarding to dho.
I tried using $regex syntax in the query.find() method but not giving the desired results. Thank You in advance
How and where to use regex for mongo db search such that I get the results?
todoRouter.get("/", async (req, res) =\> {
let query = req.query;
try {
const todos = await todoModel.find(query);
res.send(todos);
} catch (err) {
res.send(err);
}
})
If the name of the column you are searching in is name, code would look like this
const todos = await todoModel.find({"name": /.*{{your_query_param}}.*/});
I'm using TypeScript for making a GET request to get all members whose isCore is true. I've made several entries in the SQL database but it is showing null in res.json. Is the condition syntax is correct?
code:
router.get('/coreMem', async(req, res)=>{
try {
const core_member_details = await Member.findAll({
where:{
isCore: true
}
})
res.status(200).json(core_member_details);
}
catch (err) {
logger.error(`${err}`);
res.status(500).send('Internal Server/Database Error!');
}
});
I think that it, make sure that the Member model is correctly defined and that it is able to connect to the correct table in the database.
if not, a tip for you which is good debugging method:
To return all the records from the members table, you can use the findAll method without any conditions, like this:
router.get('/coreMem', async(req, res)=>{
try {
const all_member_details = await Member.findAll();
res.status(200).json(all_member_details);
},
catch (err) {
logger.error(${err});
res.status(500).send('Internal Server/Database Error!');
}
});
I want to search for my product to display on my browser by clicking the search button.
I can search products by Postman API nicely. But, I have no idea to display data by clicking the search button.
product.js
router.get("/find/:id", async (req, res) => {
try {
const product = await Product.findById(req.params.id);
res.status(200).json(product);
} catch (err) {
res.status(500).json(err);
}
});
//GET ALL PRODUCTS
router.get("/", async (req, res) => {
const qNew = req.query.new;
const qCategory = req.query.category;
try {
let products;
if (qNew) {
products = await Product.find().sort({ createdAt: -1 }).limit(1);
} else if (qCategory) {
products = await Product.find({
categories: {
$in: [qCategory],
},
});
} else {
products = await Product.find();
}
res.status(200).json(products);
} catch (err) {
res.status(500).json(err);
}
});
Navbar.js
const Navbar = () => {
return (
<Button>Search</Button>
);
};
export default Navbar;
You're going to want to use Axios to make a request from your react application.
To do this you need to install and require Axios into your react application.
This code will allow you to make a request to your express application:
async function getProduct(productID) {
try {
const response = await axios.get(`/find/${productID}`);
console.log(response);
} catch (error) {
console.error(error);
}
}
This is going to only work when you know what the ID of the product you're searching is. If you have another endpoint on your server to search for a product via name you can change the endpoint accordingly. Here are the Axios docs.
Hope this helps. Thanks!
I would like to get data from a mongodb database and pass it to the frond.
I wrote this function it works in the console i get an array that contains some elements but on the browser i get undefined. I use nodejs(express, ejs) and mongodb.
getAllOrders: function(companyName) {
client.connect().then((client)=>{
let db = client.db('data')
db.collection('order').find({companyName:companyName}).toArray(function(err, result) {
if (err) throw err
console.log(JSON.stringify(result.map(a => a.orderIdem))) // output all orderIdems
});
});
}
//App.js
app.get('/', async function(req, res) {
let orderItem = await db.getAllOrders("SuperTrader");
console.log(orderItem); // here i get a response
res.render('index', {
orderItem: orderItem,
});
});
// frontend
//index.ejs
<h2>Variable</h2>
<p><%= orderItem %></p>
//orderItem[0] also doesn't work
there is nothing you are returning from the function. try this:
getAllOrders: async function(companyName) {
return client.connect().then((client)=>{
let db = client.db('data')
return await db.collection('order').find({companyName:companyName});
});
}
I have a fairly extensive Node.js back-end with Express and pg-promise. Most of it is working perfectly as I expected it to.
Currently I am trying to create a function that deletes from multiple tables if I pass in a value for it to do so. My problem is that when I try to use req.body.cont (cont is a variable to continue) I get undefine
I have tried changing the names of the variables, trying to mimic how I sent data to the server before.
function removeUser(req, res, next) {
console.log(req.body.cont);
if (req.body.cont) {
console.log('hello');
deleteLocCustId(req, res, next, req.params.id);
}
db.result('delete from customer where id = $1', req.params.id)
.then(function(result) {
if (!req.body.cont) {
res.status(200).json({
status: 'success',
message: `Removed ${result.rowCount} customer`
});
}
})
.catch(function(err) {
console.log(err);
return next(err);
});
}
When I use this same method to create a customer it works perfectly.
function createCustomer(req, res, next) {
const newCustomer = new PQ(
'insert into customer(customer_name, ID, parent, symID) values ($1, $2, $3, $4)'
);
newCustomer.values = [
req.body.customerName,
req.body.cId,
req.body.parentName,
req.body.symPID
];
db.none(newCustomer)
.then(() => {
if (req.body.locationObject) {
return createLocation(req, res, next);
}
return null;
})
.catch(function(err) {
return next(err);
});
}
When I try to console.log(req.body.cont); I get undefined from my server.