how to modify/edit/update existing object in moralis db
Hi thanks
i have read the docs but don’t understand how i select an object to save.
my error of this code is: query.set is not a function
upDateMonster = async() => {
const MonsterCreature = Moralis.Object.extend(‘Monsters’);
const query = new Moralis.Query(MonsterCreature);
//const query = new MonsterCreature;
query.equalTo(“x”, 4);
query.set(“x”, 1337);
await query.save();
//const monster = query.first();
//monster.set(“x”, 1337);
//await monster.save();
//console.log(monster);
//return monster;
}
You cant run .save() on query.
Query is a datastructure you use to ask Moralis for certain elements that comply with some condition.
Query returns an array of results.
In order to change something in database you need to tell Moralis which element you want to change from the elements returned by the query.
If the returned array is not empty you can get the first element with .first().
You need to do like this (like you have in your code but commented out):
const monster = query.first()
monster.set("x",1337);
monster.save()
i have tried many variants but get the same error: monster.set is not a function
as if a query object has no set function.
set works with monster = new MonsterCreature(); but creates a new object in db
upDateMonster = async() => {
const MonsterCreature = Moralis.Object.extend(‘Monsters’);
const query = new Moralis.Query(MonsterCreature);
query.equalTo(“x”, 4);
const monster = query.first();
monster.set(“x”, 1337);
monster.save();
console.log(monster);
return monster;
}
Please always post your code in a formatted way here in the forum - learn how to do it here: https://discourse.stonehearth.net/t/discourse-guide-code-formatting/30587
It’s difficult to read otherwise.
Ah I see I forgot await.
Change
const monster = query.first();
To
const monster = await query.first();
It works
thank you very much, now i’m going to win the hackathon
upDateMonster = async() => {
const MonsterCreature = Moralis.Object.extend('Monsters');
const query = new Moralis.Query(MonsterCreature);
query.equalTo("x", 4);
const monster = await query.first();
monster.set("x", 1337);
monster.save();
console.log(monster);
return monster;
}