how to achieve following query with mongoid - mongoid

How to write following mongodb query with mongoid?
db.messages.find({ 
                   $or :[
{ $and : [
                                    {"receiver_id":"user1#gmail.com"},
                                    {"sender_id":"user2#hotmail.com"}
                          ]
},
                          { $and : [
{"receiver_id":"user2#hotmail.com"},
{"sender_id":"user1#gmail.com"}
]  
}
]
});

It will be same as:
Message.all.or("receiver_id":"user1#gmail.com","sender_id":"user2#hotmail.com").or("receiver_id":"user2#hotmail.com","sender_id":"user1#gmail.com")

Related

Update of nested document with update function with $set results in "The positional operator did not find the match needed from the query."

I am trying to change the price of middle in a second element of the document from 15.00 to 17.00:
/* 1 */
{
    "_id" : ObjectId("60042d16540eae75f0acd6bd"),
    "name" : "Bolonian",
    "ingredients" : [ 
        "ham", 
        "salami", 
        "becon", 
        "chili", 
        "cheese"
    ],
    "prices" : [ 
        {
            "small" : 15.0
        }, 
        {
            "middle" : 21.0
        }, 
        {
            "big" : 30.0
        }
    ]
}
/* 2 */
{
    "_id" : ObjectId("60042d16540eae75f0acd6be"),
    "name" : "Margherita",
    "ingredients" : [ 
        "tomato souce", 
        "cheese"
    ],
    "prices" : [ 
        {
            "small" : 11.0
        }, 
        {
            "medium" : 15.0
        }, 
        {
            "big" : 24.0
        }
    ]
}
With function: 
function change_price(name_of_pizza, size, new_price){
    db.pizza.update({ "name" : name_of_pizza}, {$set: { ["prices.$." + size] : new_price}});
}
    
change_price("Margherita", "middle", 17.00)
However, I receive an error: 
The positional operator did not find the match needed from the query.
How can I set the nested value of middle price from 15 to 17 in a function?
You can try arrayFilters, The filtered positional operator $[<identifier>] identifies the array elements that match the arrayFilters conditions for an update operation.
try $exists operator to check is field available
db.pizza.update(
{ "name": name_of_pizza },
{ $set: { ["prices.$[p]." + size]: new_price } },
{
arrayFilters: [
{ ["p." + size]: { $exists: true } }
]
}
)
Playground

POST https://google-translate1.p.rapidapi.com/language/translate/v2 502 (Bad Gateway) When fetching in React

An example of the rapidapi google translate API code for the JavaScript fetch method is:
fetch("https://google-translate1.p.rapidapi.com/language/translate/v2", {
"method": "POST",
"headers": {
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
"x-rapidapi-key": "MY-API-KEY",
"accept-encoding": "application/gzip",
"content-type": "application/x-www-form-urlencoded"
},
"body": {
"source": "en",
"q": "Hello, world!",
"target": "es"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
Now I copied it, and used it for the React component as follows:
fetch("https://google-translate1.p.rapidapi.com/language/translate/v2", {
method: "POST",
body: {
"source": "en",
"q": "Hello, world!",
"target": "es"
},
headers: {
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
"x-rapidapi-key": "MY-API-KEY",
"accept-encoding": "application/gzip",
"content-type": "application/x-www-form-urlencoded"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
After running the program, I get the error "POST https://google-translate1.p.rapidapi.com/language/translate/v2 502 (Bad Gateway)" on the console!
How can I have a healthy connection to the server?
this code solved the same problem for me
<script>
const key = "your key"
const qs = obj => {
return new URLSearchParams(obj).toString();
}
const word = "Hello, world";
const data = qs({
q: word,
source: "en",
target: "es",
})
const options = {
method: "POST",
url: "https://google-translate1.p.rapidapi.com/language/translate/v2",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-rapidapi-key": key,
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
},
data: data,
};
axios.request(options).then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(99, error);
});
</script>

Fetch return blob instead of text after 0.59 RN update

I update my RN app from 0.58.3 version to 0.59.4 and instead of bodyText server return bodyBlob now
I tried to use response.json() func but it doesn't help
fetch(`http://someserver `, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Accept-Language': 'ru,en;q=0.9',
},
body: '{"login":"root","password":"root"}'
})
.then((response) => {
console.log(response.json());
});
response i get is like this:
{
"type": "default",
"status": 200,
"ok": true,
"headers": {
"map": {
"x-xss-protection": "1",
"set-cookie": "jwt=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyLWNvZGUiOiJyb290LXVzZXIiLCJleHAiOjE1NTU0MjY0Mjl9.UaHzsIil8t9HtgrBF8JN0c2W-eIIkDEmb6GvO9Do0-A;Expires=Tue, 16 Apr 2019 14:53:49 +0000;Path=/;HttpOnly;SameSite=Strict",
"connection": "keep-alive",
"content-length": "360",
"content-type": "application/json;charset=utf-8",
"date": "Tue, 16 Apr 2019 13:53:49 GMT",
"server": "nginx/1.15.10"
}
},
"url": "***",
"_bodyInit": {
"_data": {
"size": 360,
"offset": 0,
"blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
}
},
"_bodyBlob": {
"_data": {
"size": 360,
"offset": 0,
"blobId": "3397402a-12dd-4dd9-8980-90924aeb416d"
}
}
}
instead of normal bodyText i get bodyBlob
Sorry, I am late with the answer. I hope it will be helpful for others.
Be careful, response.json() returns promise.
fetch(`http://someserver `, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Accept-Language': 'ru,en;q=0.9',
},
body: '{"login":"root","password":"root"}'
})
.then((response) => {
response.json().then(res => {
console.log(res);
})
});

$http get returns different than $resource get

I am trying to download user reports using a User $resource. However, the returned result comes in an object like so: (weird)
{0: "n", 1: "a", 2: "m", 3: "e", 4: ",", 5: "e", 6: "m", 7: "a", 8: "i", 9: "l", 10: ",", 11: "p", 12: "a", 13: "r", 14: "t", 15: "n", 16: "e", 17: "r", 18: ",", 19: "r", 20: "o", 21: "l", 22: "e", 23: ",", 24: "p", 25: "h", 26: "o", 27: "n", 28: "e", 29: ",", 30: "s", 31: "t", 32: "a", 33: "t", 34: "u", 35: "s", 36: "↵", 37: "M", 38: "i", 39: "c", 40: "h", 41: "a", 42: "e", 43: "l", 44: " ", 45: "J", 46: "o", 47: "r", 48: "d", 49: "a", 50: "n", 51: ",", 52: "m", 53: "j", 54: "#", 55: "m", 56: "j", 57: ".", 58: "c", 59: "o", 60: "m", 61: ",", 62: ",", 63: "a", 64: "d", 65: "m", 66: "i", 67: "n", 68: ",", 69: "8", 70: "0", 71: "1", 72: "5", 73: "6", 74: "4", 75: "1", 76: "3", 77: "6", 78: "1", 79: ",", 80: "↵", $promise: Promise, $resolved: true}
When I use $http.get everything comes as expected:
name,email,partner,role,phone,status
Michael Jordan,mj#mj.com,,admin,8015641361,
I have no idea what I am doing wrong. Here are my files:
search.controller.js (with two approaches producing different results)
$scope.downloadReport = function() {
$http.get('/api/users/download',{params:$state.params}).success(function(res) {
console.log(res)
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(res),
target: '_blank',
download: 'filename.csv'
})[0].click();
});
User.download($state.params,function(res){
console.log(res)
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(res),
target: '_blank',
download: 'Users.csv'
})[0].click();
},function(err){
console.log(err)
});
};
user.service.js (tried with and without isArray)
angular.module('Raizzle.Admin')
.factory('User', function ($resource) {
return $resource('/api/users/:id/:controller', { id: '#_id'}, {
download: {
method: 'GET',
params: {
id:'download'
}
},
changePassword: {
method: 'PUT',
params: {
controller:'password'
}
},
get: {
method: 'GET',
params: {
id:'me'
}
}
});
});
I'm guessing that $resource has a hard time returning raw data? Any ideas?
Thanks in advance!
$resource assumes the response is a JSON object and does additional processing under that assumption. You have several options here to solve your problem:
Use transformResponse to avoid parsing to JSON object (see $resource documentation about transformResponse: https://docs.angularjs.org/api/ngResource/service/$resource ), not sure that would even work.
Use $http instead of $resource.
Make the backend return a JSON object instead of plaintext.
if you use $resource, transformResponse it must be something like:
{ ...
method: "GET",
transformResponse: function(data, headersGetter, status) {
return {content: data};
}
in GET of user.service.js

SharePoint/Angular can't delete item - Error 412

Update: I have changed my Services and Controller as follows and am now receiving an Error 412 (HTTP/1.1 412 Precondition Failed). Here is my updated code:
Service:
appServices.factory('appType', ['$resource', function ($resource) {
return $resource("/_api/web/lists/getbytitle('Todo Types List')/Items(:Id)", { Id: "#Id" },
{
'query': { method: "GET", isArray: false, headers: { 'Accept': 'application/json;odata=nometadata' } },
'update': { method: 'PATCH', headers: { 'Accept': 'application/json;odata=nometadata' } },
'save': { method: 'POST', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() } },
'delete': { method: 'DELETE', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() }, 'IF-MATCH': "*" },
}
);
}]);
Relevant part of Controller:
$scope.removeType = function (type) {
appType.delete({ Id: type.Id });
console.log("Deleted" + type.ID);
}
}]);
Original Post:
I am attempting to delete an item/row in an Angular App built on top of SharePoint 2013, but when I am attempt the delete it appears to process, except nothing is removed from the SharePoint list. Using the network tab in IE, I get a 400 error.
Here is my controller:
appControllers.controller('appSettingsCtrl', ['$scope', 'appTypes', function ($scope, appTypes) {
// Retrieve Types
$scope.types = [];
appTypes.query({}, function (data) {
$scope.types = data.value;
});
// Create Types
var typeEntry = new appTypes;
$scope.addType = function () {
console.log("Clicked");
typeEntry.Title = $scope.itemtype;
typeEntry.$save();
}
// Delete types
$scope.removeType = function (type) {
appTypes.delete({}, { Id: type.ID });
console.log("Deleted" + type.ID);
}
}]);
Here is my HTML:
<table class="table table-striped">
<tr>
<th>Type</th>
<th>
Action
</th>
</tr>
<tr ng-repeat="type in types" id="type{{type.Id}}">
<td>
{{type.Title}}
</td>
<td>
<button type="button" class="btn btn-danger" data-ng-click="removeType(type)">Delete</button>
</td>
</tr>
</table>
Here is my service:
appServices.factory('appTypes', ['$resource', function ($resource) {
return $resource("/_api/web/lists/getbytitle('Todo Types List')/Items", {Id: "#Id" },
{
'query': { method: "GET", isArray: false, headers: { 'Accept': 'application/json;odata=nometadata' } },
'update': { method: 'PATCH', headers: { 'Accept': 'application/json;odata=nometadata' } },
'save': { method: 'POST', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() } },
'delete': { method: 'DELETE', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val(), 'IF-MATCH': '*' } },
}
);
}]);
Here is some sample JSON:
{
"value": [
{
"FileSystemObjectType": 0,
"Id": 5,
"ID": 5,
"ContentTypeId": "0x01004CE051F4BDBACB43BB22C234F8F497FE",
"Title": "Type 1",
"Modified": "2015-03-13T18:35:09Z",
"Created": "2015-03-13T18:35:09Z",
"AuthorId": 12,
"EditorId": 12,
"OData__UIVersionString": "1.0",
"Attachments": false,
"GUID": "9ceee022-a418-43d4-86b1-1de6d68edc47"
}
]
}
I am using following headers when removing a item from a list.
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": "*",
"X-Http-Method": "DELETE".
For me it works. Hope it helps to you too.
Blame this error on having a small typo that malformed the header (The If-Match was outside of the headers:. This is correct:
'delete': { method: 'DELETE', headers: { 'Accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose', 'X-RequestDigest': $("#__REQUESTDIGEST").val(), 'IF-MATCH': '*' } }

Resources