how to update a document use $ operator in mongodb - javascript

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")}]})

Related

MongoDB : mongoose findbyidandupdate condition not working

I want to update an array in a document where array is array of user object.
The problem is i don't want to add duplicates in this array ( not the same user more than one time).
what i do :
const updatedTopic = await Topic.findByIdAndUpdate(
// #ts-ignore
{ _id: id, 'votes.user': { $ne: req.user?._id.valueOf() } },
// #ts-ignore
{ $push: { votes: { year, comment, user: req.user } } },
{ new: true }
);
But this isn't working as you can see below :
{
"name": "Argomento 1",
"exam": {
"$oid": "62b71b9dcaf3e92ac568c729"
},
"slug": "argomento-1",
"user": {
"$oid": "62534e5798a11bcba35464f6"
},
"votes": [
{
"year": 2022,
"comment": "",
"user": {
"$oid": "62b22fd314c40b9067f84cc2" -> same user
},
"_id": {
"$oid": "62b8bbcf876b2d27570fdf86"
}
},
{
"year": 2022,
"comment": "",
"user": {
"$oid": "62b22fd314c40b9067f84cc2" -> same user
},
"_id": {
"$oid": "62b8bbd5876b2d27570fdf89"
}
}
],
"createdAt": {
"$date": {
"$numberLong": "1656168790097"
}
},
"updatedAt": {
"$date": {
"$numberLong": "1656274729989"
}
},
"__v": 0
}
I don't know why but changing findByIdAndUpdate to findOneAndUpdate works fine.
Probably findByIdAndUpdate checks only the id condition.

addToSet mongoDB not adding if one value is repeated

I have the following collection in MongoDB
[
{
"acronym": "front",
"references": [
{
"date": "2020-03-04",
"value": "5.6"
},
{
"date": "2020-03-05",
"value": "6.3"
}
]
}
]
I want to use the function $addToSet in order to add new document into references. I know that it can be done with the following code:
db.collection.update({
"acronym": "front"
},
{
$addToSet: {
"references": {
"date": "2020-03-06",
"value": "6"
}
}
})
And it will add the new document to the array references, so the result is the following:
[
{
"acronym": "front",
"references": [
{
"date": "2020-03-04",
"value": "5.6"
},
{
"date": "2020-03-05",
"value": "6.3"
},
{
"date": "2020-03-06",
"value": "6"
}
]
}
]
QUESTION: What I want to obtain is that in the case of adding a date that is already in the array, the update will no be produced.
Here is the playground: https://mongoplayground.net/p/DPER2RuROEs
Thanks!
You can add another qualifier to the update to prevent duplicated dates
db.collection.update({
"acronym": "front",
"references.date": {
$ne: "2020-03-04"
}
},
{
$addToSet: {
"references": {
"date": "2020-03-04",
"value": "6"
}
}
})
I got the solution from here

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

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

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