Mongodb findone order sub document - javascript

I have a document in mongodb and do a search with the medoto .find () mongoose it returns the following answer and I need to order a subdocument
Order by listCart for clienId
{
"success": true,
"data": [
{
"deleted": false,
"_id": "5ec4692f18b52a76bb2f278a",
"userId": "5ea8abe5d57e5a256bc25140",
"listCart": [//document order by clienId
{
"ppt": 2,
"_id": "5ec4692f18b52a76bb2f278b",
"topId": "5ea8ac05792ded26bdc4ece1",
"clienId": "5ea8abe5d57e5a256bc00001"
},
{
"ppt": 2,
"_id": "5ec4692f18b52a76bb2f278c",
"topId": "5ea8b439837acd35425fea02",
"clienId": "5ea8abe5d57e5a256bc00002"
},
{
"ppt": 2,
"_id": "5ec4692f18b52a76bb2f278d",
"topId": "5ea8ac05792ded26bdc4ece3",
"clienId": "5ea8abe5d57e5a256bc00001"
},
{
"ppt": 2,
"_id": "5ec4692f18b52a76bb2f278e",
"topId": "5ea8b439837acd35425fea04",
"clienId": "5ea8abe5d57e5a256bc00002"
}
],
"createdAt": "2020-05-19T23:18:07.345Z",
"updatedAt": "2020-05-19T23:18:07.345Z",
"__v": 0
}
],
"message": "Request successful"
}
Thank you

Related

Remove the rights of the child user after updating the parent

I use mongoose, and I need, in case the owner decided to stop paying for access to a certain brand (or tab, or type), for example, to remove it from a child.
Child Document
{
"_id": {
"$oid": "childId"
},
"firstName": "childname",
"lastName": "childname",
"email": "childmail#gmail.com",
"password": "hashpass",
"avatar": "avatar",
"active": true,
"grant": {
"analytic": {
"brands": true,
"competition": true,
"advanced": true,
"settings": true
},
"entity": {
"brands": [
"62b602fab0513b08cbbc58cf",
"5e2b64350abd833af61c8186"
],
"competitors": [
{
"competitors": [
"628cf4763b65341158242c97",
"5e2b64350abd833af61c8186",
"62226613937930680ce70de7"
]
},
{
"competitors": [
"62226613937930680ce70de7",
"628cf4763b65341158242c97",
"62b602fab0513b08cbbc58cf"
]
}
],
"categorys": [
"5f31a884d318436258f1c1ef",
"5e2081c80a44092668c29a47",
"5e20856d0a44092668c29a48",
],
"providers": [
"5f52869819f2df47af4afafa",
"5f5a4c51a030d76e5ed555f7",
"5dc2aff3e820a760dd23f6af",
"5f59200da030d76e5ed54e21",
],
"types": [
"structure",
"point of interest"
],
"limits": []
},
"user": {
"historical_data": true,
"allowAndUpdate": true
}
},
"pId": {
"$oid": "63add6ae1cf67918efa856c9"
},
"crdAt": {
"$date": {
"$numberLong": "1672337405101"
}
},
"updAt": {
"$date": {
"$numberLong": "1672337405101"
}
},
"__v": 0
}
Parent Document
{
"_id": {
"$oid": "parentId"
},
"firstName": "parentname",
"lastName": "parentname",
"email": "parentemail#gmail.com",
"password": "hashpass",
"avatar": "pass",
"active": true,
"grant": {
"analytic": {
"brands": true,
"competition": false,
"advanced": true,
"settings": true
},
"entity": {
"brands": [
"62b602fab0513b08cbbc58cf",
"5e2b64350abd833af61c8186"
],
"competitors": [
{
"_id": "62b602fab0513b08cbbc58cf",
"competitors": [
"628cf4763b65341158242c97",
"5e2b64350abd833af61c8186"
]
},
{
"_id": "5e2b64350abd833af61c8186",
"competitors": [
"62226613937930680ce70de7",
"628cf4763b65341158242c97",
"62b602fab0513b08cbbc58cf"
]
}
],
"categorys": [
"5f31a884d318436258f1c1ef",
"5e2081c80a44092668c29a47"
],
"providers": [
"5f52869819f2df47af4afafa",
"5f5a4c51a030d76e5ed555f7",
"5dc2aff3e820a760dd23f6af"
],
"types": [
"structure",
"point of interest"
],
"limits": []
},
"user": {
"child_users": true,
"historical_data": true,
"allowAndUpdate": true
}
},
"crdAt": {
"$date": {
"$numberLong": "1672337070171"
}
},
"updAt": {
"$date": {
"$numberLong": "1672337107440"
}
},
"__v": 0
}
Both users (child and owner) have their objects with access stored in the database, and we need to subtract the owner object from the child object
the unset function in mongo is powerless here( I've been struggling with this problem for a week now

how to update a document use $ operator in mongodb

I'm trying to update a document, this is my code
I'm new to the mongodb I'm trying to update a nested array of object this is my query please tell me what is wrong with this query
Full data link ---> link
I tried below code but it's modifying entire seat_staus
db.seats.updateOne({"show_seats.showByDate.shows.showSeats._id" :ObjectId("62b16d9ff48ce9a5a15a79d3")}, {$set:{'show_seats.$[].showByDate.shows.$[].showSeats.$[].seat_status': true }})
db.seats.updateOne(
{ 'show_seats.$.showByDate.shows.$.showSeats.$._id': new ObjectId('62b0d1a72f155a7ad94cc831')},
{ $set:{
'show_seats.$[].showByDate.shows.$[].showSeats.$[].seat_status': false
}
}
)
and this is my data look like
{
"_id": {
"$oid": "62b0c3342f155a7ad94cc81c"
},
"totalShowByDay": "2",
"totalShowDays": 4,
"movieId": {
"$oid": "62b04c782828dd04f0d1c1ad"
},
"screenId": {
"$oid": "62b04b8e2828dd04f0d1c1ac"
},
"createdAt": 1655751476553,
"showId": {
"$oid": "62b0c3342f155a7ad94cc6db"
},
"show_seats": [{
"showByDate": {
"ShowDate": "2022-06-20",
"shows": [{
"showTime": "2022-06-20T10:00",
"showSeats": [{
"_id": {
"$oid": "62b0c3342f155a7ad94cc6dc"
},
"seat_number": "1",
"tag_name": "A",
"seat_status": false,
"user_id": false,
"price": "110",
"seats_category": "CLASSIC",
"show_time": "2022-06-20T10:00"
}, {
"_id": {
"$oid": "62b0c3342f155a7ad94cc6dd"
},
"seat_number": "2",
"tag_name": "A",
"seat_status": false,
"user_id": false,
"price": "110",
"seats_category": "CLASSIC",
"show_time": "2022-06-20T10:00"
finally I found the answer It's been two day that I stuck with this problem
db.seats.updateOne({"show_seats.showByDate.shows.showSeats._id" :ObjectId("62b16d9ff48ce9a5a15a79d6")},{$set:{"show_seats.$[].showByDate.shows.$[].showSeats.$[elem].seat_status":"my name is hrithik"}},{arrayFilters:[{"elem._id":ObjectId("62b16d9ff48ce9a5a15a79d6")}]})

MongoDb return both matched results and matched results on subdocument

Hello i am trying to get my database to return both matched and empty results on a sub-document.
I am joining two tables using aggregate and lookup, below is the code
db.collection.aggregate([
{
$addFields: {
cut_off_date: { $toDate: "$shipment_cutoff_date" },
},
},
{
$lookup: {
from: "updates",
localField: "_id",
foreignField: "shipment_id",
as: "updates",
},
},
{
$match: {
"updates.description": { $ne: "All updates completed" },
},
},
]);
Challenge is i am trying to get All rows where all updates have been completed as well as all empty updates. If i remove the match parameters i get all the results including where the updates have been completed and i am trying to avoid doing a foreach after getting all my results.
Here is a snippet of the result without the match
{
"_id": "609927e31233700004370cfb",
"title": "Hello World",
"createdAt": "2021-05-10T12:32:35.799Z",
"updatedAt": "2021-05-10T15:58:59.149Z",
"updates": []
},
{
"_id": "60940ad73ced476b2d0b3626",
"createdAt": "2021-05-06T15:27:19.814Z",
"updatedAt": "2021-05-10T12:49:08.167Z",
"updates": [
{
"_id": "60952c0ed31c6283f302eb23",
"post_id": "60940ad73ced476b2d0b3626",
"description": "This is an update description",
"createdAt": "2021-05-07T12:01:18.815Z",
"updatedAt": "2021-05-07T12:01:18.815Z",
},
]
},
{
"_id": "60940ad73ced476b2d0b3626",
"createdAt": "2021-05-06T15:27:19.814Z",
"updatedAt": "2021-05-10T12:49:08.167Z",
"updates": [
{
"_id": "60952c0ed31c6283f302eb23",
"post_id": "60940ad73ced476b2d0b3626",
"description": "All updates completed",
"createdAt": "2021-05-07T12:01:18.815Z",
"updatedAt": "2021-05-07T12:01:18.815Z",
},
]
}
Here is a snippet of what i will like to achieve after the match
{
"_id": "609927e31233700004370cfb",
"title": "Hello World",
"createdAt": "2021-05-10T12:32:35.799Z",
"updatedAt": "2021-05-10T15:58:59.149Z",
"updates": []
},
{
"_id": "60940ad73ced476b2d0b3626",
"createdAt": "2021-05-06T15:27:19.814Z",
"updatedAt": "2021-05-10T12:49:08.167Z",
"updates": [
{
"_id": "60952c0ed31c6283f302eb23",
"post_id": "60940ad73ced476b2d0b3626",
"description": "This is an update description",
"createdAt": "2021-05-07T12:01:18.815Z",
"updatedAt": "2021-05-07T12:01:18.815Z",
},
]
},
I am trying to get the results without the section where update description is not "All updates completed
Any help here please, MondoDb version is 4+
You can use $filter
$facet to categorize incoming doucment into two. 1. updates == empty array and 2. update != empty array
$redact use to keep or eliminate the document based on the condition we give
$concatArray to combined to both arrays which were produced after $facet
$unwind to deconstruct the array
$replaceRoot to make to root
He is the script
db.collection.aggregate([
{
"$facet": {
"emptyUpdates": [
{
"$match": {
$expr: { $eq: [ "$updates", [] ] }
}
}
],
"withoutUpdate": [
{
"$match": {
$expr: { $ne: [ "$updates", [] ] }
}
},
{
"$redact": {
"$cond": [
{
"$anyElementTrue": {
"$filter": {
"input": "$updates",
"cond": {
$eq: [ "$$this.description","All updates completed" ]
}
}
}
},
"$$PRUNE",
"$$KEEP",
]
}
}
]
}
},
{
"$project": {
combined: {
"$concatArrays": ["$emptyUpdates", "$withoutUpdate" ]
}
}
},
{ "$unwind": "$combined" },
{
"$replaceRoot": {"newRoot": "$combined" }
}
])
Working Mongo playground
Let me know anything goes wrong

mongoose unable to make nested search through "field.attributes"

newFormName = req.body.name;
newFormQuestions = req.body.questions;
formId = req.body.formId;
User.updateOne(
{
"forms._id": formId,
},
{
$set: {
"forms.$.name": newFormName,
"forms.$.questions": newFormQuestions,
},
},
(errUpdate, resultUpdate) => {
if (errUpdate) {
return res.status(500).json({ sucess: false, error: errUpdate });
} else {
return res.status(200).json({ sucess: true, data: resultUpdate });
}
}
);
the above code is responsible to update certain field in the user database.
Example of how user data looks like
[{
"enrolledEventID": [],
"isOrganiser": true,
"isAdmin": false,
"forms": [
{
"questions": [
{
"questionType": "Text",
"textInputLabelName": "asdsadsad"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
}
],
"_id": "5f6070b5002a5249b050bd1e",
"name": "Test Form 4",
"dateCreated": "2020-09-15T07:43:49.389Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Text",
"textInputLabelName": "asdsadsad"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
}
],
"_id": "5f607140cd6faa39241f7c8a",
"name": "Test Form 56",
"dateCreated": "2020-09-15T07:46:08.012Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Rating",
"textInputQuestionTitle": "asdasdasd",
"totalRating": 0
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasdasd"
}
],
"_id": "5f6315145e6c794e78bcce73",
"name": "New Form",
"dateCreated": "2020-09-17T07:49:40.307Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Rating",
"textInputQuestionTitle": "asdasdasdsadad",
"totalRating": 0
}
],
"_id": "5f6316895e6c794e78bcce74",
"name": "New Formasdasdasd",
"dateCreated": "2020-09-17T07:55:53.537Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Text",
"textInputLabelName": "asdsadsad"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
}
],
"_id": "5f632b0f12f05d5028c96942",
"name": "Test Form 23232323",
"dateCreated": "2020-09-17T09:23:27.137Z",
"__v": 0
}
],
"_id": //id,
"fullname": //name,
"email": //hotmail,
"password": //password,
"__v": 0
},
{
"enrolledEventID": [],
"isOrganiser": true,
"isAdmin": false,
"forms": [],
"_id": //id,
"fullname": //name,
"email": //email,
"password": //password,
"__v": 0
} ]
and the problem is that the match will always return 0, I'm new to mongoose and it seems that I should be able to access to the forms._id through "forms._id" in the criteria after done some research, what did I do wrong ?
I have ensured that the formId is existed in the user data.
Make sure newFormQuestions have the same object keys with questions.
Do console.log for every step you aren't sure of.
As an alternative for this mongoose update, use
const temp = User.find({forms._id:formId}) first,
then you could use User.save() after assigning the value into the object you've found.
Good Luck ^^

Waterline Sails JS doesn't work

I've using associations in Sails JS. I've been building an ecommerce app, in which multiple models are associated to one another, but one of associated doesn't work.
In my controller, I'm trying like this:
'synchronize' : function(req,res,next){
var owner = req.param('owner'),
store = req.param('store'),
items = req.param('items'),
localCart = {
'items' : items,
'owner' : owner,
'store' : store
},
updatedCart = {};
// get cart first
PosCart.findOrCreate({
'owner' : owner,
'store' : store
},localCart)
.populate('items')
.then(function(serverCart){
if(!serverCart) throw 'Kesalahan Sistem';
// update server cart
_.each(localCart.items, function(item,index){
var _server_index = {};
// check if product exist
_server_index =_.findIndex(serverCart.items, function(_item){
return _item.product === item.product.id &&
_item.productCustomize === item.productCustomize.id &&
_.isEqual(_item.attributes,item.attributes)
});
// product already exist but have different quantity
if(_server_index > -1){
item.quantity = (item.quantity > serverCart.items[_server_index].quantity)?
item.quantity : serverCart.items[_server_index].quantity ;
serverCart.items[_server_index] = _.clone(item);
}else{
// this is new items
serverCart.items.push(_.clone(item));
}
});
// update cart then
return PosCart.update(serverCart.id, serverCart);
})
.then(function(carts){
if(!carts) throw 'Kesalahan Sistem';
// return new updated cart
// 2 level populate
updatedCart = _.clone(carts[0]);
return [
PosCart.findOne(updatedCart.id).populate('items'),
PosItem.find({'id':updatedCart.item}).populate('product'),
PosItem.find({'id':updateCart.item}).populate('productCustomize')
];
})
.spread(function(cart,items){
if(!cart) throw 'kesalahan sistem'
_.each(cart.items,function(item,index){
cart.items[index] = _.find(items,function(_item){
return _item.id === item.id;
});
});
return res.json(cart);
})
.catch(function(error){
next(error);
});
}
And In My model, I'm trying like this
PosCart.js
attributes: {
items : { collection : 'PosItem', via : 'cart' },
// owner
owner : { model : 'CrmCustomer' },
// store referrer
store : { model : 'SystemStore' }
}
PosItem.js
attributes: {
product : { model : 'PosProduct' },
productCustomize : { model : 'PosCustomProduct' },
variant : { model : 'PosProductVariant' },
attributes : { type : 'json', defaultsTo : {} },
quantity : { type : 'integer', defaultsTo : 1 },
// owner
cart : { model : 'PosCart' },
wishlist : { model : 'PosWishlist' }
}
The PosItem.find({'id':updateCart.item}).populate('productCustomize') doesn't populate in PosItem. If I try to add to cart the 'productcustom' property, like product, it'll show it's ID.
[
{
"product": {
"display": "5636fe51effd3d4508d16cc8",
"materials": [],
"store": "5636fd43effd3d4508d16cb5",
"name": "Penny",
"basePrice": 250000,
"category": "5636fe14effd3d4508d16cc7",
"attributes": {
"Bahan": [
"Kulit"
],
"Ukuran": [
"38"
]
},
"desc": "Lorem ipsum dolor sit amet",
"published": true,
"createdAt": "2015-11-02T06:10:25.296Z",
"updatedAt": "2015-11-02T06:10:25.395Z",
"id": "5636fe51effd3d4508d16cc9"
},
"variant": {
"name": "5636fe51effd3d4508d16cc9-Bahan:Kulit-Ukuran:38",
"Bahan": "Kulit",
"Ukuran": "38",
"product": "5636fe51effd3d4508d16cc9",
"additionalPrice": 0,
"createdAt": "2015-11-02T06:10:25.508Z",
"updatedAt": "2015-11-02T06:10:25.508Z",
"id": "5636fe51effd3d4508d16cca"
},
"cart": {
"store": "5632e638954e0b843f285faa",
"createdAt": "2015-11-02T06:13:28.708Z",
"updatedAt": "2015-11-02T06:13:28.738Z",
"id": "5636ff08effd3d4508d16cce"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Ukuran": "38"
},
"createdAt": "2015-11-02T06:13:28.757Z",
"updatedAt": "2015-11-02T06:13:28.757Z",
"id": "5636ff08effd3d4508d16cd0"
},
{
"variant": {
"name": "5637016deffd3d4508d16cdc-Bahan:Kulit-Soles:Outsole-Ukuran:38",
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38",
"product": "5637016deffd3d4508d16cdc",
"additionalPrice": 25000,
"createdAt": "2015-11-02T06:23:41.862Z",
"updatedAt": "2015-11-02T06:24:53.995Z",
"display": [
{
"zoom": "file/65e1d275-c3a7-4502-a0fe-6f5ac299d00d.jpg",
"gallery": "file/ecbf0705-88ce-41dc-8ba2-4755041b623e.jpg",
"thumbnail": "file/0db0e9e8-9294-4df0-b173-7d6de822786a.jpg",
"active": true
}
],
"id": "5637016deffd3d4508d16cdd"
},
"cart": {
"store": "5636fd43effd3d4508d16cb5",
"owner": "56370d92509c2c470a3d33ac",
"createdAt": "2015-11-02T07:15:47.026Z",
"updatedAt": "2015-11-02T07:16:11.749Z",
"id": "56370da3509c2c470a3d33af"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38"
},
"createdAt": "2015-11-02T07:16:11.809Z",
"updatedAt": "2015-11-02T07:16:11.809Z",
"id": "56370dbb509c2c470a3d33b1"
}
]
Anyone can help me to solve this to be result at the bottom? :)
[
{
"product": {
"display": "5636fe51effd3d4508d16cc8",
"materials": [],
"store": "5636fd43effd3d4508d16cb5",
"name": "Penny",
"basePrice": 250000,
"category": "5636fe14effd3d4508d16cc7",
"attributes": {
"Bahan": [
"Kulit"
],
"Ukuran": [
"38"
]
},
"desc": "Lorem ipsum dolor sit amet",
"published": true,
"createdAt": "2015-11-02T06:10:25.296Z",
"updatedAt": "2015-11-02T06:10:25.395Z",
"id": "5636fe51effd3d4508d16cc9"
},
"productCustomize": {
"display": "5636fe51effd3d4508d16dd9",
"materials": [],
"store": "5636fd43effd3d4508d16cb5",
"name": "Beefroll",
"basePrice": 250000,
"category": "5636fe14effd3d4508d16cc7",
"attributes": {
"Bahan": [
"Kulit"
],
"Ukuran": [
"38"
]
},
"variant": {
"name": "5636fe51effd3d4508d16cc9-Bahan:Kulit-Ukuran:38",
"Bahan": "Kulit",
"Ukuran": "38",
"product": "5636fe51effd3d4508d16cc9",
"additionalPrice": 0,
"createdAt": "2015-11-02T06:10:25.508Z",
"updatedAt": "2015-11-02T06:10:25.508Z",
"id": "5636fe51effd3d4508d16cca"
},
"cart": {
"store": "5632e638954e0b843f285faa",
"createdAt": "2015-11-02T06:13:28.708Z",
"updatedAt": "2015-11-02T06:13:28.738Z",
"id": "5636ff08effd3d4508d16cce"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Ukuran": "38"
},
"createdAt": "2015-11-02T06:13:28.757Z",
"updatedAt": "2015-11-02T06:13:28.757Z",
"id": "5636ff08effd3d4508d16cd0"
},
{
"variant": {
"name": "5637016deffd3d4508d16cdc-Bahan:Kulit-Soles:Outsole-Ukuran:38",
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38",
"product": "5637016deffd3d4508d16cdc",
"additionalPrice": 25000,
"createdAt": "2015-11-02T06:23:41.862Z",
"updatedAt": "2015-11-02T06:24:53.995Z",
"display": [
{
"zoom": "file/65e1d275-c3a7-4502-a0fe-6f5ac299d00d.jpg",
"gallery": "file/ecbf0705-88ce-41dc-8ba2-4755041b623e.jpg",
"thumbnail": "file/0db0e9e8-9294-4df0-b173-7d6de822786a.jpg",
"active": true
}
],
"id": "5637016deffd3d4508d16cdd"
},
"cart": {
"store": "5636fd43effd3d4508d16cb5",
"owner": "56370d92509c2c470a3d33ac",
"createdAt": "2015-11-02T07:15:47.026Z",
"updatedAt": "2015-11-02T07:16:11.749Z",
"id": "56370da3509c2c470a3d33af"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38"
},
"createdAt": "2015-11-02T07:16:11.809Z",
"updatedAt": "2015-11-02T07:16:11.809Z",
"id": "56370dbb509c2c470a3d33b1"
}
]
You have so many fields! :-)
My suggestion to find the problem would be to start backwards and then get to where you want.
Go to https://github.com/balderdashy/waterline-docs/blob/master/models/associations/associations.md and see if you can make the basic association model work.
Then step by step start adding your complexity. If you follow this gradual approach eventually you will stumble upon where the problem lies.
Good luck!

Categories