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

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 ^^

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

Get field of JSON in Javascript Console

I have a JSON like this, how to get the value of StatusDescription? I tried many times but the result is undefined. Here is my JSON:
{
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
I'm using in my NodeJS app, like myapp.js, and console.log()
Try this
I stored your sample json in variable json
var json = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
Accessed it like below
console.log(json.data.items[0].origin_info.trackinfo[0].StatusDescription);
Items is an array and we took array element 0.
trackinfo again is an array and we took array element 0.
We can change array index or loop through and get required values.
You have to iterate through your items and trackinfo to get to StatusDescription. Try this one.
const data = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
const items = data.data.items.map(item => item)
const trackinfo = items.map(item => item.origin_info.trackinfo).flat()
console.log(trackinfo)
const statusDescription = trackinfo.map(trackinfo => trackinfo.StatusDescription)
console.log(statusDescription)

Mongodb findone order sub document

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

Aggregate array occourances

I have a set of documents (posts) which have an array of users mentioned in each post.
{
"title": "Some post title",
[ ... ]
"mentions": ["johnsmith", "johndoe", "paul"]
}
I want to aggregate a list of unique mentions, and the number of times they've been mentioned across all posts. For example:
[{ user: "johnsmith", count: 5 }, { user: "benlewis", count: 9 }, { user: "johndoe", count: 1 }]
With Mongo, I'd do something like:
"mentions": [{
"$unwind": "$mentions"
}, {
"$group": {
"_id": "$mentions",
"count": { "$sum": 1 }
}
}]
What's the equivalent in Elasticsearch?
You can use a Terms aggregation for that. A small (5.x) example:
PUT test
{
"mappings": {
"test" : {
"properties": {
"title": {
"type": "text"
},
"mentions": {
"type": "keyword"
}
}
}
}
}
POST test/test/1
{
"title": "Some post title",
"mentions": [
"johnsmith",
"johndoe",
"paul"
]
}
POST test/test/2
{
"title": "Some post title 2",
"mentions": [
"johnsmith"
]
}
GET test/_search
{
"size": 0,
"aggs": {
"test": {
"terms": {
"field": "mentions",
"size": 10
}
}
}
}
Gives the following response:
"aggregations": {
"test": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "johnsmith",
"doc_count": 2
},
{
"key": "johndoe",
"doc_count": 1
},
{
"key": "paul",
"doc_count": 1
}
]
}
}
}
Hope this helps :)

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