For each post I have this structure:
{
"_id": "5dfd3b918937d40b98afd3f8",
"user": "5deea38cfc84f42590e01942",
"title": "test",
"description": "description test",
"category":
{
"0": "1",
"1": "101"
},
"phone": "+1",
"country": "USA",
"city": "NY",
"options": {
"transaction_type": ""
},
"date": "2019-12-20T21:22:25.940Z",
}
In express I using bottom code for find posts by category id but not working what I should to do?
router.get("/category/:category", async (req, res) => {
try {
const posts = await Post.find({
category: { $all: req.params.category }
}).sort({ date: -1 });
if (!posts) {
return res.status(404).json({ msg: "Ads not found" });
}
const resultPosts = posts.slice(req.query.start, req.query.count);
res.json(resultPosts);
} catch (err) {
console.error(err.message);
if (err.kind === "ObjectId") {
return res.status(404).json({ msg: "Ads not found" });
}
res.status(500).send("Server Error!");
}
});
Related
I need to delete a location object from the locations array. It is deeply nested. I followed mongoose documentation but my attempts didn't work:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
},
{
"locationName": "Loc3",
"count": 30,
"_id": "7cb0c1f51a91c384846d65f8b2ae"
}
]
},
{more lists}
Attempt:
router.post("/lists/deleteLoc", (req, res) => {
const {
listId,
list_id,
item_id,
location_id
} = req.body;
List.updateOne({
"lists.listId": listId,
"lists._id": list_id
}, {
$pull: {
"lists.$.items": {
locations: {
$elemMatch: {
_id: location_id
})
.then(() => res.json({
msg: "location removed"
}))
.catch((err) => res.status(400).json({
msg: "Error: " + err
}));
});
If the request location_id was "7cb0c1f51a91c384846d65f8b2ae" it should delete the last location from the array. The desired result:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
}
]
},
{more lists}
I've tried basically all variations of this, but none have worked.
I'm also not sure if making a router.post or an axios.post request for deletion is correct. Should this be axios.delete and router.delete?
I've tried this in one of my similar DB and worked!
List.updateOne({ "listId": yourListId },
{
'$pull': {
'items.$[item].locations': { "_id": yourLocationId }
}
}, {
"arrayFilters": [
{
"item._id": yourItemId
}
]
}, function (err) {
if (err) {
res.json(err)
} else {
res.json({ message: "Updated" })
}
})
}
You've to put the values that're inside your DB from the object that you want to delete.
So if you want to delete the object with
"locationname" : "Loc3"
You should use
var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";
Try it out!
I have below JSON:
{
"program_objective": "",
"program_type": "Post Graduate",
"creation_date": "2020-01-04T04:45:28.418Z",
"dstatus": "",
"_id": "5e101e26a96cc905745721b0",
"program_name": "Hardware",
"short_code": "Hdw",
"program_induc_date": "2020-01-28T18:30:00.000Z",
"program_cat": "Certificate",
"program_years": "0",
"program_months": "6",
"depart_id1": "Msc IT ",
"PEO": [
{
"_id": "5e1300d826c155310c6ae384",
"peo": "Hardware",
"weight": 212
},
{
"_id": "5e1300d826c155310c6ae383",
"peo": "Hardware",
"weight": 212
}
],
"Name": [],
"PO": [],
"__v": 0
}
I want the PEO value from above JSON but when I am trying to get "PEO":{}, it is returning null.
router.route('/getprogram/:id/PEO/').get((req, res, next) => {
addmissionForm.programSchema.findById(req.params.id, (error, data) => {
console.log(data.PEO)
if (error) {
return next(error)
} else {
res.json(data)
}
})
});
I'm new to Node.js and was deploying Paypal rest SDK, I'm stuck at this point, I want to pass a parameter from 'success' api that called by the paypal API, to the original API called by angular
//paypal
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': '',
'client_secret': ''
});
app.post('/pay-online', (req, res) => {
console.log('request came')
console.log(req.body.fare.toString())
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "localhost:3000/success",
"cancel_url": "localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": req.body.fare,
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": req.body.fare
},
"description": "This is the payment description."
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
res.send(payment.links);
}
});
});
var getSuccess = app.get('/success', (req, res) => {
var paymentId = req.query.paymentId;
var payerId = { payer_id: req.query.PayerID };
paypal.payment.execute(paymentId, payerId, function (error, payment) {
console.log(payment.state)
if (error) {
console.error(JSON.stringify(error));
} else {
if (payment.state == 'approved') {
console.log('payment completed successfully');
} else {
console.log('payment not successful');
}
}
});
});
My question that I need to pass (payment.state) to the page that called 'pay-online' API, how can I pass the parameter back to the page?
You can return a JSON object to the page which calls the 'pay-online' API as follows if you can get the state from "paypal.payment.create" method.
app.post('/pay-online', (req, res) => {
console.log('request came')
console.log(req.body.fare.toString())
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "localhost:3000/success",
"cancel_url": "localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": req.body.fare,
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": req.body.fare
},
"description": "This is the payment description."
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
res.send({
payment:payment.links,
state:payment.state . <----JSON Property
});
}
});
});
If you need to call the "paypal.payment.execute" method to get the payment state then you have to call "paypal.payment.execute" method inside the '/pay-online' method's success block.
I have the documents as follows:
{
"_id": {
"$oid": "5bf662551a0ffc2f40c91945"
},
"categories": [
"angular"
],
"title": "1",
"details": "1",
"url": "undefined",
"category": {
"$oid": "5bf135657d6f2c69a527186d"
},
"created_at": {
"$date": "2018-11-22T08:01:25.418Z"
},
"__v": 0
}
I want to find all documents based on category id. I tried this:
articleModel
.find({category: req.params.id})
.sort({ $natural: -1 })
.exec(function(err, blogs) {
if (err) {
throw err;
}
console.log("get blogs by category ", blogs);
res.json({
success: true,
message: "blogs by category",
blogs: blogs
});
});
but it returns empty array.
use new mongoose.Types.ObjectId(YOUR_ID) when find using mongoose object ID :
articleModel
.find({"category": new mongoose.Types.ObjectId(req.params.id)})
.exec(function(err, blogs) {
if (err) {
throw err;
}
console.log("get blogs by category ", blogs);
res.json({
success: true,
message: "blogs by category",
blogs: blogs
});
});
i am new to mongo db.
I am trying to render my toyota car manufacturer alone.
written mongo db query code but its not producing results.
var cursor = db.collection('user-data').find( { carManufacturer: { $eq: toyota } } );
can you guys tell me how to fix it providing my code below
router.get('/cars', function(req, res, next) {
console.log("kumari5");
res.render('cars.hbs');
var toyota = [];
mongo.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('user-data').find( { carManufacturer: { $eq: toyota } } );
cursor.forEach(function(doc, err) {
assert.equal(null, err);
toyota.push(doc);
}, function() {
db.close();
res.render('data', {items: toyota});
console.log(toyota);
});
});
});
{
"_id": ObjectId("590a2495bd1d3a356074d36e"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["toyota", "19"],
"Expiry": null
}
{
"_id": ObjectId("347834783478873478788734"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["bmw", "19"],
"Expiry": null
}
{
"_id": ObjectId("34634738468299221182338989"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["benz", "19"],
"Expiry": null
}
{
"_id": ObjectId("47347347834783487437834734"),
"DateBough": "21",
"Owner": "Female",
"carManufacturer": ["toyota", "19"],
"Expiry": null
}