How to delete object with Id in Realm or Primary Key? - react-native

I have below object :
obj1 = [{ id = 1, name = "abc"}, {id=2, name="pqr"}, {id=3, name="xyz"}]
I need to delete an object with id=2 where id is Primary Key too.
Below method using to delete the object
const collection = RealmDB.realm
.objects("StudentName")
.filtered(`id= $0`, '65');
RealmDB.realm.write(() => {
RealmDB.realm.delete(collection);
});
But it is not working with id object can anyone please suggest better way to do this ?
But still that object is there so may I know what is wrong here.

const id = 1;
realm.write(()=>{
realm.delete(realm.objectForPrimaryKey('Baby',id));
})
Try this.

Hello resolved an issue by following query with no error
const collection = RealmDB.realm
.objects('StudentName')
.filtered('id= $0', `65`);
RealmDB.realm.write(() => {
RealmDB.realm.delete(collection);
Thank you

Related

Get roles by name in a 'guildMemberAdd' handler

Since member.guild.roles.get('roleName') no longer works. I'd like to know if there's an alternative to it.
message.guild.roles.cache.find(role => role.name == 'My Role Name') is not an option, since I don't have access to message object inside the 'guildMemberAdd' handler.
My code works fine using the role id, but I'd like to make it usable for other servers.
** updating my question
This is my code:
const role1 = 'the id number here'; ---> this one I'd like to be by name
const role2 = 'the id number here');
if (collected.first().emoji.name === '😎') {
member.roles.add(role1);
} if (collected.first().emoji.name === '🟩'){
member.roles.add(role2);
} else { return}
You can access the guild from GuildMember
client.on('guildMemberAdd', member => {
// member.guild.roles.cache.find(...) - Callback similar to Array#find()
// member.guild.roles.cache.get(...) - string id parameter only
});

How to delete items from an array in Vue

I have a function called updateAnswer with multiple dynamic parameters.
updateAnswer(key, answer, array = false) {
if (array) {
if(this.answers.contains.find(element => element === answer)) {
//Delete item from array if already element already exists in this.answers.contains array.
} else {
Vue.set(this.answers, key, [...this.answers.contains, answer]);
}
} else {
Vue.set(this.answers, key, answer);
}
},
I'd like to know how delete an item in the array if the value already exists in the array.
You can use method called splice:
Just reference on your array and set values in the brackets the first is referenced on the position, the second is how many datas you want to splice/delete.
The function looks like this:
this.array.splice(value, value)
Lets see on an example - you have array food= [apple, banana, strawberry] than I'm using this.food.splice(1,1)..
my array looks now like this food = [apple, strawberry] - first value in my brackets are the position, the second one is the amount of "numbers" you want to delete.
Hopefully this helps you out!
I suppose each value in this.answers.contains is unique?
Anyways, if you just want to delete the item if already exists, I suggest filter(). It should look like below:
if(this.answers.contains.find(element => element === answer)) {
this.answers.contains = this.answers.contains.filter(c => c !== answer)
}
Also, the if condition if(this.answers.contains.find(element => element === answer)) could also be replaced by if(this.answers.contains.includes(answer))
Hope that could help you.

second entity query is executed with errors

I have 2 linq queries. First query does nothing because of unique index and this is OK. But second also does nothing while it should add records . If I bypass first query second query works. Should I refresh entity ? How ?
foreach (var product in productList)
{
cc2nexo_SubiektProduct newproduct = new cc2nexo_SubiektProduct();
newproduct.Name = product.Name;
newproduct.VAT = product.VAT;
newproduct.Id = product.Id;
foreach (var stawkaVAT in myNexo_ExitoEntities.StawkiVat)
{
if (stawkaVAT.Stawka * 100 == tryconvert_dec(newproduct.VAT))
{
newproduct.VAT_Id = stawkaVAT.Id;
}
}
myNexo_ExitoEntities.cc2nexo_SubiektProduct.Add(newproduct);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
}
var orders = (from myorders in myNexo_ExitoEntities.temp_SubiektOrderList
select myorders).ToList();
foreach (var order in orders)
{
cc2nexo_SubiektOrderList neworder = new cc2nexo_SubiektOrderList();
neworder.Data_utworzenia_sprawy = tryconvert_date(order.Data_utworzenia_sprawy);
neworder.Data_modyfikacji_sprawy = tryconvert_date(order.Data_modyfikacji_sprawy);
neworder.Data_umowy = tryconvert_date(order.Data_umowy);
neworder.Id = order.Id;
myNexo_ExitoEntities.cc2nexo_SubiektOrderList.Add(neworder);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
Debug.WriteLine(neworder.LastName);
}
I am receiving an error
Cannot insert duplicate key row in object 'dbo.cc2nexo_SubiektProduct' with unique index 'K_ID'. The duplicate key value is (1).The statement has been terminated
The reason of problem was SurroundWithTryCatchDB procedure not listed in my question. Because first query caused exception due to unique index all next SaveChanges did not work. I have changed my first query to work with unique values and now everything is OK.

Upsert in KnexJS

I have an upsert query in PostgreSQL like:
INSERT INTO table
(id, name)
values
(1, 'Gabbar')
ON CONFLICT (id) DO UPDATE SET
name = 'Gabbar'
WHERE
table.id = 1
I need to use knex to this upsert query. How to go about this?
So I solved this using the following suggestion from Dotnil's answer on Knex Issues Page:
var data = {id: 1, name: 'Gabbar'};
var insert = knex('table').insert(data);
var dataClone = {id: 1, name: 'Gabbar'};
delete dataClone.id;
var update = knex('table').update(dataClone).whereRaw('table.id = ' + data.id);
var query = `${ insert.toString() } ON CONFLICT (id) DO UPDATE SET ${ update.toString().replace(/^update\s.*\sset\s/i, '') }`;
return knex.raw(query)
.then(function(dbRes){
// stuff
});
Hope this helps someone.
As of knex#v0.21.10+ a new method onConflict was introduced.
Official documentation says:
Implemented for the PostgreSQL, MySQL, and SQLite databases. A
modifier for insert queries that specifies alternative behaviour in
the case of a conflict. A conflict occurs when a table has a PRIMARY
KEY or a UNIQUE index on a column (or a composite index on a set of
columns) and a row being inserted has the same value as a row which
already exists in the table in those column(s). The default behaviour
in case of conflict is to raise an error and abort the query. Using
this method you can change this behaviour to either silently ignore
the error by using .onConflict().ignore() or to update the existing
row with new data (perform an "UPSERT") by using
.onConflict().merge().
So in your case, the implementation would be:
knex('table')
.insert({
id: id,
name: name
})
.onConflict('id')
.merge()
I've created a function for doing this and described it on the knex github issues page (along with some of the gotchas for dealing with composite unique indices).
const upsert = (params) => {
const {table, object, constraint} = params;
const insert = knex(table).insert(object);
const update = knex.queryBuilder().update(object);
return knex.raw(`? ON CONFLICT ${constraint} DO ? returning *`, [insert, update]).get('rows').get(0);
};
Example usage:
const objToUpsert = {a:1, b:2, c:3}
upsert({
table: 'test',
object: objToUpsert,
constraint: '(a, b)',
})
A note about composite nullable indices
If you have a composite index (a,b) and b is nullable, then values (1, NULL) and (1, NULL) are considered mutually unique by Postgres (I don't get it either).
Yet another approach I could think of!
exports.upsert = (t, tableName, columnsToRetain, conflictOn) => {
const insert = knex(tableName)
.insert(t)
.toString();
const update = knex(tableName)
.update(t)
.toString();
const keepValues = columnsToRetain.map((c) => `"${c}"=${tableName}."${c}"`).join(',');
const conflictColumns = conflictOn.map((c) => `"${c.toString()}"`).join(',');
let insertOrUpdateQuery = `${insert} ON CONFLICT( ${conflictColumns}) DO ${update}`;
insertOrUpdateQuery = keepValues ? `${insertOrUpdateQuery}, ${keepValues}` : insertOrUpdateQuery;
insertOrUpdateQuery = insertOrUpdateQuery.replace(`update "${tableName}"`, 'update');
insertOrUpdateQuery = insertOrUpdateQuery.replace(`"${tableName}"`, tableName);
return Promise.resolve(knex.raw(insertOrUpdateQuery));
};
very simple.
Adding onto Dorad's answer, you can choose specific columns to upsert using merge keyword.
knex('table')
.insert({
id: id,
name: name
})
.onConflict('id')
.merge(['name']); // put column names inside an array which you want to merge.

Mongoskin findAndModify ID object id

Using nodejs, mongoskin.. I'd like to return the updated doc so Im using findAndModify, however the query {_id: "someid"} doesn't work. I think I need to use {id: ObjectID{'someid'} as the query. How do I get the ObjectId type into JS?
try this:
ObjectID = require('mongoskin').ObjectID
{_id: new ObjectID("someid")}
Here is a solution
var mongo = require("mongoskin");
var conn = mongo.db(YOUR_DETAILS);
var BSON = mongo.BSONPure;
this enables you to convert your id int, string or whatever using:
conn.collection(YOUR_COLLECTION).find({_id:new BSON.ObjectID(YOUR_ID)})
Hope that helps!
You can do something like:
yourCollection = db.collections('yourCollection');
Then
{ _id: yourCollection.id("someId") }