Find all documents by Id in mongoose? - javascript

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

Related

Issue while updating nested data createEntityAdapter RTK query

I am working on the chat that is utilising RTK Query with entity adapters. We created nested normalised createEntityAdapter . I want to update the message key from onCacheEntryAdded, but not able to update nested object. I'm attaching the query endpoint code along with sample response.
RTK Query Endpoint
endpoints: builder => ({
getMessages: builder.query({
query: ({ orderId, userId, channel }) => {
return {
url: `/messages?orderId=${orderId}&userId=${userId}`,
method: 'GET',
}
},
transformResponse(response, meta, arg) {
return messagesAdapter.setAll(messagesAdapter.getInitialState(), [
{
id: `${arg.orderId}-${arg.userId}`,
isTyping: false,
channel: arg.channel,
orderId: arg.orderId,
messages: messagesAdapter.addMany(
messagesAdapter.getInitialState(),
response,
),
},
])
},
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved, cacheData },
) {
try {
await cacheDataLoaded
updateCachedData(draft => {
messagesAdapter.updateOne(draft, {
id: '62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72',
changes: {
messages: messagesAdapter.updateOne(
messagesAdapter.getInitialState(),
{
id: '62da7221bc0eb3a259fc2256',
changes: {
message: 'updated message',
},
},
),
},
})
})
} catch {
// no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
// in which case `cacheDataLoaded` will throw
}
await cacheEntryRemoved
},
providesTags: (result, error, arg) => {
console.log('providesTags', result, error, arg)
return ['chat']
},
}),
}),
Sample response
{
"ids": [
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72"
],
"entities": {
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72": {
"id": "62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72",
"isTyping": false,
"channel": "62d7d9266599a9f0c3bcdaba",
"orderId": "62d529f60be7549be1f53df3",
"messages": {
"ids": [
"62da7221bc0eb3a259fc2256",
"62da724dbc0eb3a259fc2260",
"62da75559f7a23f89a0958d4",
"62da94e59f7a23f89a0958ed"
],
"entities": {
"62da7221bc0eb3a259fc2256": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "dsds",
"sentAt": "2022-07-22T09:47:13.000Z",
"id": "62da7221bc0eb3a259fc2256"
},
"62da724dbc0eb3a259fc2260": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello nm",
"sentAt": "2022-07-22T09:47:57.000Z",
"id": "62da724dbc0eb3a259fc2260"
},
"62da75559f7a23f89a0958d4": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "b",
"sentAt": "2022-07-22T10:00:53.000Z",
"id": "62da75559f7a23f89a0958d4"
},
"62da94e59f7a23f89a0958ed": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello there",
"sentAt": "2022-07-22T12:15:31.000Z",
"id": "62da94e59f7a23f89a0958ed"
}
}
}
}
}
}

How To $pull From Deeply Nested Document (mongoose)

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!

How can find in object at object of array in express

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

Node.js Paypal rest sdk

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.

iteration on Datasource in Angular

I want to make a function which iterates through an array of object and set the property status to false.
The array of obj is a datasource on angular table.
this.lightService.getLamp()
.subscribe(
(response) => {
this.lampData = response;
this.dataSource.data = response;
},
(error) => {
console.log('error ' + error);
}
The Data source
{
"id": 1,
"group" : 1,
"name": "Lamp 1",
"connected": " Not Connected",
"status": true,
"address": "1",
"channel": "All",
"temperature": 3200,
"error": false,
"errorMessage": "Not Working at this moment"
},
{
"id": 2,
"group" : 2,
"name": "Lamp 2",
"connected": "Connected",
"status": true,
"address": "2",
"channel": "All",
"temperature": 6500,
"error": false,
"errorMessage": "Not Working at this moment"
},
{
.....
}
]
You can use the .map operator for iterating through all the objects in an array. I suppose the below code should work for you.
this.lightService.getLamp()
.subscribe(
(response) => {
this.lampData = response;
this.dataSource.data = response;
this.dataSource.data.map(item => {
item.status = false
})
},
(error) => {
console.log('error ' + error);
}

Categories

Resources