How to update a field in Fauna Database - reactjs

I am working in fauna DB. I have a confusion for writing an query to update a field . From the given array object I want to update the Boolean fields ( "presentation", "keyTakeaways", "whitepaper", "downloadAll") with the reference to the SegmentAnonymousID. I am adding the code that I tried. Can someone help me to sort out the problem.
[{
"ref": Ref(Collection("Downloads"), "322568726157197900"),
"ts": 1643884359510000,
"data": {
"SegmentAnonymousID": "57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a",
"response": {
"firstname": "test ",
"lastname": "test 1",
"email": "test#gmail.com",
"company": "test",
"presentation": false,
"keyTakeaways": false,
"whitepaper": false,
"downloadAll": false
}
}
},
{
"ref": Ref(Collection("Downloads"), "322484599970071113"),
"ts": 1643870069845000,
"data": {
"SegmentAnonymousID": "15ba9e0d-e646-4d31-beaa-b2a4d3eac56f",
"response": {
"firstname": "test 4",
"lastname": "test4",
"email": "test#gmail.com",
"company": "test",
"presentation": false,
"keyTakeaways": false,
"whitepaper": false,
"downloadAll": false
}
}
}]
The code I tried
const result = await faunaClient.query(
q.Update(
q.Select("ref", q.Get(q.Match(q.Index("SegmentAnonymousID"), "57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a")), { data: { response: { "presentation": true } } })
)
)

Your query has brackets in the wrong place. As written, the object containing the new data appears as the "default" value for the Select call. You'll likely have better success with this update (reformatted to show function calls and parameters better):
const result = await faunaClient.query(
q.Update(
q.Select(
"ref",
q.Get(
q.Match(
q.Index("SegmentAnonymousID"),
"57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a"
)
)
),
{
data: {
response: {
presentation: true
}
}
}
)
)

Related

How to filter JSON data based on another JSON data in typescript

I have 2 JSON Data 1. Payers 2. Rules. I need to filter Payers JSON data based on PayerId from Rules JSON data.
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}}
Rules JSON file
{
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
}]}
I need to filter Payers JSON data based on Rules JSON data if PayerID matches
I need output like below
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "34567",
"name": "Test Payer3"
}
}
How to filter?
You can use Array.filter like that (based on your data structure):
const filteredPayers = payersObj.Payers.filter((p) => rulesObj.Rules[0].Criteria[0].payerId.includes(p.payerId));
I can't figure out why your Rules json looks like this, I guess you have multiple rules. If so, you will need to iterate over each rule and invoke includes. Same for Criteria.
Code will check each rule and each critirias
and will return payers if payerId found in any of the given rules of any criteria
const payers = {
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}]}
const rules = {
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
]
}
const data = payers.Payers.filter(payer => rules.Rules.findIndex(rule => rule.Criteria.findIndex(criteria => criteria.payerId.includes(payer.payerId)) != -1) !== -1)
console.log(data)

How to update array inside MongoDB document

Can someone help me with a solution to update an array object inside the MongoDB document, I've tried a couple of methods but still it's to updating, here is my document that I want to update the array in the document.
{
"title": "Products",
"description": "test",
"image": "bdd8510d75f6e83ad308d5f306afccef_image.jpg",
"_created_at": "2021-06-07T20:51:08.316Z",
"ratingCount": 0,
"ratingTotal": 0,
"placeListSave": [
{
"objectId": "g70brr45pfi",
"name": "Kale",
"email": "null",
"strBrandLogo": "84de8865e3223d1ca61386355895aa04_image.jpg",
"storeNumber": "56",
"phone": "0815342119",
"createdAt": "2021-06-10T10:19:53.384Z",
"image": "ad1fb7602c2188223fd891a52373cb9d_image.jpg"
},
{
"objectId": "0qokn33p773",
"name": "Apple",
"email": null,
"strBrandLogo": null,
"storeNumber": "01",
"phone": "011 393 8600",
"createdAt": "2021-06-11T03:11:17.342Z",
"image": "8cfcbf2bcb5e3b4ea8ade44d3825bb52_image.jpg"
}
]
}
So I only want to update the apple object and change the data, I've tried the following code but doesn't seem to work.
`
var db = client.db("test");
try {
db.collection("ShoppingCentres").updateOne({
"title": req.body.product,
"placeListSave.objectId": req.body.id,
}, {
$set: {
"placeListSave.$.email": req.body.email,
"placeListSave.$.storeNumber": req.body.storeNumber,
"placeListSave.$.phone": req.body.phone,
"placeListSave.name": req.body.name,
},
});
res.json("client");
} catch (e) {
console.log("verify", e);
}
});`
arrayFilters seems suitable here:
db.collection.update({
"title": "Products",
"placeListSave.objectId": "0qokn33p773",
},
{
$set: {
"placeListSave.$[x].email": "test#some.email",
"placeListSave.$[x].storeNumber": "test",
"placeListSave.$[x].phone": "test",
"placeListSave.$[x].name": "test"
}
},
{
arrayFilters: [
{
"x.objectId": "0qokn33p773"
}
]
})
explained:
Add array filter called "x" with the objectId for the element that you need to update and use this filter in the $set stage to update the necessary elements.
Hint: To speed up the update you will need to add index on title field or compound index on title+placeListSave.objectId
playground

How can I remove all JSON objects that have a certain key/value pair from an array of JSON objects?

I want to filter a dataset this like:
For example here's some fake dataset:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Donna",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Tia",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tuxedo"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
I want to filter out everything that has "livesInCity": false:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
How can I do this? Is this possible?
In python I believe it's something like this, but I do not know how to get started in Swift:
people = [person for person in people if person.livesInCity == True]
Also, how can I filter this data set above to look like this - I want to categorize by type in name.
{
"tabby": ["Sakura", "Linn"],
"tuxedo": ["Dora"],
}
Any help will be very appreciated!
As already mentioned in the comments, you can't work directly on JSON objects in Swift. They need to be converted first.
You can parse your JSON to a Swift object and then perform filtering, grouping etc.
struct Person: Codable {
let name: String
let hasChildren: Bool
let livesInCity: Bool
let pets: [Pet]
}
struct Pet: Codable {
let cats: [String]
let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)
Then you can filter your parsedObjects:
let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })
or in shorter (swiftier) version:
let filteredObjects = parsedObjects.filter { $0.livesInCity }
You can also try to group by pet type:
var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
person.pets.forEach { pet in
if let _ = groupedDict[pet.type] {
groupedDict[pet.type]!.append(person.name)
} else {
groupedDict[pet.type] = [person.name]
}
}
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]
If at any point you want to convert your objects back to JSON you can use:
let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}
Note
For the sake of simplicity I used forced optional unwrapping (!) when decoding/encoding objects. You may want to use do-try-catch instead (to catch errors).

How to filter embedded array in mongo document with morphia

Given my Profile data looks like below, I want to find the profile for combination of userName and productId
and only return the profile with the respective contract for this product.
{
"firstName": "John",
"lastName": "Doe",
"userName": "john.doe#gmail.com",
"language": "NL",
"timeZone": "Europe/Amsterdam",
"contracts": [
{
"contractId": "DEMO1-CONTRACT",
"productId": "ticket-api",
"startDate": ISODate('2016-06-29T09:06:42.391Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "ticket",
"permission": "createTicket"
},
{
"activity": "ticket",
"permission": "updateTicket"
},
{
"activity": "ticket",
"permission": "closeTicket"
}
]
}
]
},
{
"contractId": "DEMO2-CONTRACT",
"productId": "comment-api",
"startDate": ISODate('2016-06-29T10:27:45.899Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "comment",
"permission": "createComment"
},
{
"activity": "comment",
"permission": "updateComment"
},
{
"activity": "comment",
"permission": "deleteComment"
}
]
}
]
}
]
}
I managed to find the solution how to do this from the command line. But I don't seem to find a way how to accomplish this with Morphia (latest version).
db.Profile.aggregate([
{ $match: {"userName": "john.doe#gmail.com"}},
{ $project: {
contracts: {$filter: {
input: '$contracts',
as: 'contract',
cond: {$eq: ['$$contract.productId', "ticket-api"]}
}}
}}
])
This is what I have so far. Any help is most appreciated
Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression(??))
Note... meanwhile I found another solution which does not use an aggregation pipeline.
public Optional<Profile> findByUserNameAndContractQuery(String userName, String productId) {
DBObject contractQuery = BasicDBObjectBuilder.start(Contract._productId, productId).get();
Query<Profile> query =
getDatastore()
.createQuery(Profile.class)
.field(Profile._userName).equal(userName)
.filter(Profile._contracts + " elem", contractQuery)
.retrievedFields(true, Profile._contracts + ".$");
return Optional.ofNullable(query.get());
}
I finally found the best way (under assumption I only want to return max. 1 element from array) to filter embedded array.
db.Profile.aggregate([
{ $match: {"userName": "john.doe#gmail.com"}},
{ $unwind: "$contracts"},
{ $match: {"contracts.productId": "comment-api"}}
])
To match according to your first design you could try the projection settings with morphia aggregation pipeline.
Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression("$filter", new BasicDBObject()
.append("input", "$contracts")
.append("as", "contract")
.append("cond", new BasicDBObject()
.append("$eq", Arrays.asList('$$contract.productId', "ticket-api")));
Also see the example written by the morphia crew around line 88 at https://github.com/mongodb/morphia/blob/master/morphia/src/test/java/org/mongodb/morphia/aggregation/AggregationTest.java.

How to extract array on nodejs

Im making the api for showing the user info, so I write the code like this
res.json({"Status" : true , "User" : rows });
then i get the result
{
"Status": true,
"User": [
{
"userid": 821786,
"fullname": "undefined",
}
]
}
But I want the result like this
{
"Status": true,
"userid": 821786,
"fullname": "undefined"
}
How can I do this ?
I tried
res.json({"Status" : true ,"Type":"Google", rows });
but it gives me
{
"Status": true,
"rows": [
{
"userid": 821786,
"fullname": "undefined",
}
]
}
I can sure that only one result will be queried so i dont want to use array
Try this:
var result = rows[0];
result.Status = true;
res.json(result);

Resources