Bruce Stuart
Posts: 0
Joined: Fri Oct 24, 2014 4:42 am

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Evening,

I've read a few posts here about limitations around not being able to remove multiple objects from a collection essentially with one query .... so - I would just like to ensure.

Mongodb - supports remove correct? ( http://docs.mongodb.org/manual/refere... )

Our implementation or release of this db does not? Correct?
(previous posts here allude to that fact and can't find any reference to 'remove' in the docs - unless referring to removing elements of an array - on an array element of a collection).

so - the recommended method for removing objects that meet a query would be:

  • Issue a read query that matches the result set you want to delete.

  • in the success event of the read query (datasource)- spin through the 'data' array - build an array of keys that are to be deleted when spinning through the data array.

  • In a for-while loop - read back the array - and for each element in the array - call a dataservice to delete the row instance from the collection??

    Is that right? or is there some much simpler way (my hope lol)

    Thanks for the help in advance,

    Bruce

Yurii Orishchuk
Posts: 0
Joined: Fri Feb 14, 2014 8:20 am

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Hi Bruce,

Yes that's correct way..

You can create Server script to do it more efficiently.

Here is a steps:

  1. Create server script.

  2. Use following JS code:

    precode

    var dbId = "52fdXXXXc89917&quot
    var collectionName = "tempCollection&quot
    var query = [] ;

    try
    {

    var params = {};

    params.criteria =
    {
    //Here is your where clause
    "_id": {"$in": ["1", "2", "3"]}
    };

    queryResult = Collection.query(dbId, collectionName, params);

    for(var i = 0; i < queryResult&#46;length; i++){
    Collection&#46;deleteObject(dbId, collectionName, queryResult&#46;_id);
    queryResult
    };

    response&#46;success({message: (queryResult&#46;length + " items deleted")});
    }
    catch (e)
    {
    response&#46;success("message: " + e&#46;message + "ncode: " + e&#46;code);
    }

    /code/pre

    More info about server code here: http://devcenter.appery.io/documentat...

    Regards.

Bruce Stuart
Posts: 0
Joined: Fri Oct 24, 2014 4:42 am

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Yurii,

Super helpful. I've done the reading suggested - and I'm going to move forward with creating the script - it will keep my UI more straightforward ...i hope.

So - if I want authenticated users to use this script only - I'm going to pass in user id and password information ? or is it just as well if I pass it the session token - like the appery database api's - and then I can leverage that - inside my script? if I do that - I presume I use the session token in my query... along with the DB id, collection name, etc..

Just for clarity my use case is I'm collecting information that a user wants to send in an email --- at a future date in my UI. The UI also allows attachments (photos mostly) - that can be sent with the email message - again , in the future - with certain recurrence options.

The attachments I'm keeping in a separate - linked db. So - if a user enters an email with attachments - and then deletes it during it's lifecycle - I need to remove the attachments as well.

So - the use case here will be to pass in a UserID and a message ID pair ( uniqifiers for the email message table) (along with the header information). Query the attachments database for a match (user id and message ID_ - return results (0,1 or more attachments associated with the message), gather the keys that need to delete, and then do the deleting.

anything else magical I should know given that scenario? Looks like I'd just modify the where clause you have above with my parameters - and then pass through the results as you've outlined above??

The same code looks great - and I'm off to create my second server code example (worked through the tutorial here about 5 months ago)...

thanks again,

Bruce

Yurii Orishchuk
Posts: 0
Joined: Fri Feb 14, 2014 8:20 am

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Hi Bruce,

You need to add login processing to your script.

Here is an example:

pre

var DB_id = "&#46;&#46;&#46;&#46;&#46;&#46;";

var userName = "userValue"; &#47;&#47;Store the user name
var userPass = "passwordValue"; &#47;&#47;and its password

try {
var loginResponse = DatabaseUser&#46;login(DB_id, userName, userPass); &#47;&#47;Login the user and save its sessionToken to the variable

&#47;&#47;Here you can use session token&#46;
var token = loginResponse&#46;sessionToken

}catch (e) {
&#47;&#47;If credentials not correct&#46;
response&#46;success("message: " + e&#46;message + "ncode: " + e&#46;code);
}

/pre

What about where clause - you should search needed attachments with needed criteria.. For example in your attachments collection should be fields "userId" and "messageId" or appropriate pointers.

Regards.

Bruce Stuart
Posts: 0
Joined: Fri Oct 24, 2014 4:42 am

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Yurii,

Thanks for the help. I wanted to post back here my working server code - in case someone else might find this helpful. Your hints plus the docs - spot on - and writing the code was easier and more efficient than doing it in my front end. I've of course changeid's and masterkeys to be safe.....

Thanks again.....
--------------------------------------Working server script to delete rows 'in bulk' that
-- match a where clause - the where clause comes into the script as a parameter - there are 2 parameters inbound - the userid and the whereclause --------

***********************************************************************************

var responseBody = {},
requestParams = {},
paramKeys = request.keys();

for (var key = 0; key < paramKeys.length; key++) {
requestParams[paramKeys[key]] = request.get(paramKeys[key]);
}
responseBody.requestBody = request.body();
responseBody.requestParams = requestParams;
responseBody.method = request.method; // responseBody.method now contains string "GET" or "POST".--- here I used GET.

// code to do the work. Login to the database with the master key,
// and then - delete the requested rows...

var dbId = "14bad3d2-e20f-xxxx-xxxx-xxxxxxxxxx"; // the api key from the control panel of your database
var smasterkey= 'xxxxxxx-xxxxx-xxxx-xxxxxxxxxxxxx' // the master key from the control panel of your database
var collectionName = "nameofcollectionwhereyouwanttodoabulkdelete"; // the name of the collection
// login....
var swhereclause = request.get("swhereclause"); //Store the where clause from the inbound paramter
var susername = request.get('susername') ; // username from the inbound parameter
console.log( "the where clause is:" + swhereclause + " the user name is:" + susername ); // log the parms to the console for debugging
var query = [] ;
var spassword = '' ;
try
{
result = {};
console.log('inside try loop');
var token = DatabaseUser.login(dbId , susername , null , smasterkey ).sessionToken; //Login the user and save its sessionToken to the variable
result.token = token; //Save it token to the result too
console.log('I am logged in');
// now logged in...
var params = {};
params.criteria = swhereclause ;
console.log('about to execute query');
queryResult = Collection.query(dbId, collectionName, params);
console.log('Rows returned:' + queryResult.length );
for(var i = 0; i < queryResult.length; i++){
console.log('executing delete object:' + queryResult.id );
Collection.deleteObject(dbId, collectionName, queryResult.id);
queryResult
};
console.log('there was success');
responseBody.success = queryResult.length + " items deleted";
responseBody.error = "";
}
catch (e)
{
console.log('there was an error: ' + e.message + ' Error ncode was:' + e.code );
responseBody.success = "";
responseBody.error = "message: " + e.message + "ncode: " + e.code;
}
console.log('outside try loop')
console.log(responseBody);
response.success(responseBody, "application/json");
// don't forget to logout of the db ... I know I did....
DatabaseUser.logout(dbId, token);
console.log('logged out of db & script complete');
// golf clap occurs here when you get the results in your service - and then you can query them from your UI...

Bruce Stuart
Posts: 0
Joined: Fri Oct 24, 2014 4:42 am

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Oh - and when imported using the service - add service - from server script you get this constructed service - that's easy to execute from your code (and get results from as well):

Image

Image

Image

Evgene Karachevtsev
Posts: 12
Joined: Mon Apr 28, 2014 1:12 pm

Need to make sure - I've Read other posts here on deleting objects in a collection that match a where clause

Hello Bruce,

Thank you for the update, sure this information will be useful for others.

Return to “Issues”