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!
Related
I made an API on Node.js, If I send some params I get the response, it's the same person but different language info, I would like to present it like in the second example I haven't been able to figure it out.
How I'm getting the data
[
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "english",
}
]
how I want to see it
[
{
"Id": 1,
"ced": "123",
"Name": "Andres",
}
"Idiomas":
[
{
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
}
]
]
export default {
el: "myFormPerson",
data() {
return {
results:[],
ced:'',
}
},
methods: {
submitForm() {
axios.get('http://localhost:8080/person/' + this.ced)
.then((response) => {
this.results = response.data;
//console.log(this.results);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
//console.log(this.ced);
},
}
}
How I see it right now [1]: https://i.stack.imgur.com/ezHgH.png
Rather than pointlessly trying to get the format you want in the MySQL result (not possible) - work with the JSON to convert it to what you want
this.results=Object.values(response.data.reduce((acc,{Id,ced,Name,...rest})=>(acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));
working example
const have = [{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "english",
}
];
const want = Object.values(have.reduce((acc,{Id,ced,Name,...rest}) => (acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));
console.log(want);
I have this data stored in database.
{
"_id": "62fa5aa25778ec97bc6ee231",
"user": "62f0eb5ebebd0f236abcaf9d",
"name": "Marketing Plan",
"columns": [
{
"name": "todo",
"_id": "62fa5aa25778ec97bc6ee233",
"tasks": [
{
"title": "Task Four testing 2",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes test",
"completed": false,
"_id": "62ff74bfe80b11ade2d34456"
},
{
"name": "do homework",
"completed": false,
"_id": "62ff74bfe80b11ade2d34457"
}
],
"_id": "62ff74bfe80b11ade2d34455"
}
]
},
{
"name": "doing",
"_id": "62fa5aa25778ec97bc6ee234",
"tasks": []
},
{
"name": "done",
"_id": "62fa5aa25778ec97bc6ee235",
"tasks": []
}
],
"__v":0
}
I want to be able to return a single object with the id equal to the req.params.id, in this case that would be 62ff74bfe80b11ade2d34455.
{
"title": "Task Four testing 2",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes test",
"completed": false,
"_id": "62ff74bfe80b11ade2d34456"
},
{
"name": "do homework",
"completed": false,
"_id": "62ff74bfe80b11ade2d34457"
}
],
"_id": "62ff74bfe80b11ade2d34455"
}
I researched stackoverflow and came across this potential solution: Mongoose retrieve one document from nested array which implemented the aggregate framework. But when I test this in postman, the request isn't made.
const getTask = asyncHandler(async (req, res) => {
const task = await Board.aggregate([
{
$match: {
"columns.tasks._id": req.params.id,
},
},
{
$project: {
columns: {
$first: {
$filter: {
input: "$columns.tasks",
cond: {
$eq: ["$$this._id", req.params.id],
},
},
},
},
},
},
{
$replaceRoot: {
newRoot: "$columns",
},
},
]);
});
Having an array inside an array complicates the query a bit, but here's one way to retrieve the data you want.
db.Board.aggregate([
{
$match: {
"columns.tasks._id": req.params.id
}
},
{"$unwind": "$columns"},
{
$match: {
"columns.tasks._id": req.params.id
}
},
{
"$project": {
"task": {
"$first": {
"$filter": {
"input": "$columns.tasks",
"cond": {"$eq": ["$$this._id", req.params.id]}
}
}
}
}
},
{"$replaceWith": "$task"}
])
Try it on mongoplayground.net. [The mongoplayground.net example uses "62ff74bfe80b11ade2d34455" rather than req.params.id.]
I'm making a kanban task management app and I'm trying to remove a task with the _id: req.params.id which has the value of 62fa5ae05778ec97bc6ee23a. I tried the following:
const task = await Board.findOneAndUpdate(
{
"columns.tasks._id": req.params.id,
},
{ $pull: { "columns.$.tasks.$._id": req.params.id } },
{ new: true }
);
But I get the error Too many positional (i.e. '$') elements found in path'columns.$.tasks.$._id'
I searched for a while and came across arrayFilters from the docs but I'm struggling a lot to understand how to implement it for this particular need.
{
"_id": "62fa5aa25778ec97bc6ee231",
"user": "62f0eb5ebebd0f236abcaf9d",
"name": "Marketing Plan",
"columns": [
{
"name": "todo",
"_id": "62fa5aa25778ec97bc6ee233",
"tasks": [
{
"title": "Task Four",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes",
"completed": false,
"_id": "62fa5ae05778ec97bc6ee23b"
},
{
"name": "do homework",
"completed": false,
"_id": "62fa5ae05778ec97bc6ee23c"
}
],
"_id": "62fa5ae05778ec97bc6ee23a"
}
]
},
{
"name": "doing",
"_id": "62fa5aa25778ec97bc6ee234",
"tasks": []
},
{
"name": "done",
"_id": "62fa5aa25778ec97bc6ee235",
"tasks": []
}
],
"__v": 0
}
You need to use $[] positional operator in order to pull from the nested array. Try running this query:
db.Board.updateOne({
"_id" : "62fa5aa25778ec97bc6ee231",
}, {
$pull: { 'columns.$[].tasks': { '_id': '62fa5ae05778ec97bc6ee23a' } }
});
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"
}
}
}
}
}
}
I am working on a forum and after retrieving all comments for a post, I am trying to sort them into comments and sub-comments.
Each comment has its own unique ID as well as the ID of its parent. In cases were the comment is made directly on the post (ie. top level comment) the parent ID equals the forum post ID.
"doc": [{
"id": "73emgNKLiCdzcREyCLtg",
"data": {
"likeCount": 0,
"body": "comment text",
"createdAt": "2020-01-16T21:42:37.782Z",
"forumPostId": "csRvt21qDqSeLqXv3mAr", //forumPostID is same as ParentId
"parentId": "csRvt21qDqSeLqXv3mAr"
}
}, {
"id": "2sRvt21qDqSeLqXv3mAr",
"data": {
"likeCount": 0,
"body": "subcomment text",
"createdAt": "2020-01-16T21:42:37.782Z",
"forumPostId": "csRvt21qDqSeLqXv3mAr",
"parentId": "73emgNKLiCdzcREyCLtg"
}
}, {
"id": "1242sR1qDqSeLqXv3mAr",
"data": {
"likeCount": 1,
"body": "subcomment text",
"createdAt": "2020-01-16T21:42:37.782Z",
"forumPostId": "csRvt21qDqSeLqXv3mAr", //forumPostID is same as ParentId
"parentId": "csRvt21qDqSeLqXv3mAr"
}
}, {...
I am trying to store the sorted comments in an object called "comments." Each generation of comments and sub-comments is sorted based on "likeCount" and "CreatedAt", and each comment contains all of its sub-comments. The final result would look something like this:
"comments": [{
"id": "1242sR1qDqSeLqXv3mAr",
"data": {
"likeCount": 1, //comment with most likes moved to top
"body": "subcomment text",
"createdAt": "2020-01-16T21:42:37.782Z",
"forumPostId": "csRvt21qDqSeLqXv3mAr",
"parentId": "csRvt21qDqSeLqXv3mAr"
},
"comments": {}
}, {
"id": "73emgNKLiCdzcREyCLtg",
"data": {
"likeCount": 0,
"body": "comment text",
"createdAt": "2020-01-16T21:42:37.782Z",
"forumPostId": "csRvt21qDqSeLqXv3mAr",
"parentId": "csRvt21qDqSeLqXv3mAr"
},
"comments": {
"id": "2sRvt21qDqSeLqXv3mAr",
"data": {
"likeCount": 0,
"body": "subcomment text",
"createdAt": "2020-01-16T21:42:37.782Z",
"forumPostId": "csRvt21qDqSeLqXv3mAr",
"parentId": "73emgNKLiCdzcREyCLtg"
}
}
}, {...
*Note that sub-comments can have sub-comments (ie. there can by infinite generations)
I have been reading up on find(), filter() and sort() but can't wrap my head around exactly what a function/loop to accomplish this would look like.
Any and all help/guidance would be appreciated!
You could collect the items as a tree and sort the items.
var data = [{ id: "73emgNKLiCdzcREyCLtg", data: { likeCount: 0, body: "comment text", createdAt: "2020-01-16T21:42:37.782Z", forumPostId: "csRvt21qDqSeLqXv3mAr", parentId: "csRvt21qDqSeLqXv3mAr" } }, { id: "2sRvt21qDqSeLqXv3mAr", data: { likeCount: 0, body: "subcomment text", createdAt: "2020-01-16T21:42:37.782Z", forumPostId: "csRvt21qDqSeLqXv3mAr", parentId: "73emgNKLiCdzcREyCLtg" } }, { id: "1242sR1qDqSeLqXv3mAr", data: { likeCount: 1, body: "subcomment text", createdAt: "2020-01-16T21:42:37.782Z", forumPostId: "csRvt21qDqSeLqXv3mAr", parentId: "csRvt21qDqSeLqXv3mAr" } }],
tree = function (data, root) {
var t = {};
data.forEach(o => {
Object.assign(t[o.id] = t[o.id] || {}, o);
t[o.data.parentId] = t[o.data.parentId] || {};
t[o.data.parentId].children = t[o.data.parentId].children || [];
t[o.data.parentId].children.push(t[o.id]);
t[o.data.parentId].children.sort((a, b) => b.data.likeCount - a.data.likeCount);
});
return t[root].children;
}(data, data[0].data.forumPostId);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
In the end, I added an "order by likes" parameter to the database query then I used a forEach loop to cycle through all the raw comment data and push comments with PrentIds = to the comment-in-question's ID to its comment array. It's not the prettiest function in the world but here is the result:
.
.
.
.then((data) => {
forumPostData.comments = [];
buildComments(forumPostData, data);
return res.json(forumPostData);
})
.
.
.
function buildComments(object, data) {
data.forEach((doc) => {
if (doc.data().parentId === object.id) {
let comm = {
id: doc.id,
data: doc.data(),
comments: []
};
object.comments.push(comm);
let index = object.comments.findIndex(x => x.id === doc.id);
buildComments(object.comments[index], data);
}
});
}