[SOLVED] Save events data in a new table

We have two kinds of events Event A and EventB.
EventA is emitted whenever user creates a question and eventB is created whenever somebody upvotes a question.
Both are being saved in their respective tables in Mongodb.
I want to create a third table with new entry being added whenever a new question is created. Whenevr there is a new upvote, update the questionId in this table.

One way to do this is to run Mongodb aggregation query on EventB and find out the toal number of upvotes on each question.

using afterSave hooks for EventA and EventB tables helps?

Shall i use it on cloudFunctions?
I couldnt find any relevant documentation for that.

https://docs.moralis.io/moralis-server/cloud-code/triggers#beforesave

Moralis.Cloud.afterSave("Comment", (request) => {
  const query = new Moralis.Query("Post");
  query.get(request.object.get("post").id)
    .then(function(post) {
      post.increment("comments");
      return post.save();
    })
    .catch(function(error) {
      console.error("Got an error " + error.code + " : " + error.message);
    });
});

Is comment a collection in MongoDB? Will it be created automatically if it doesnt exists?
Is Post a document in this collection? If yes then what “post” is?

I guess comment is a function name.
post is the collection Name

I want Comment function to be run automatically
HOw i will achieve that?

it looks like Post is a different collection, Comment is a collections also that will not be created automatically. it looks like that code inserts data in Post collection when a new Comment is added.

that function will be run automatically when a row is saved in Comment collection

How do I save the the data being stored in QuestionCreated into another collection called as QuestionTipSum?

Moralis.Cloud.beforeConsume("QuestionCreated", (event) => {
  	if (event && event.confirmed{
        const query = new Moralis.Query("QuestionTipsSum");
        //No idea on how to do that.
     }
});

please check this for creating and saving new objects in the database https://docs.moralis.io/moralis-server/database/objects#saving-objects


Also - please don’t use beforeConsume it will be removed in the next release

You can use beforeSave or afterSave in order to track changes in the DB

Thanks for the great help.

Last question,

Moralis.Cloud.afterSave("QuestionCreated", async function(request) {
    const confirmed = request.object.get("confirmed");
    console.log(request.object);
    if (confirmed) {
    const Question = Moralis.Object.extend("QuestionTipsSum");
    const question = new Question();
    question.set("questionId", request.object.get("questionId"));
    question.set("sessionId", request.object.get("sessionId"));
    question.set("value", request.object.get("value"));
    question.set("createdBy", request.object.get("createdBy"));
    question.set("createdAt", request.object.get("createdAt"));
    question.set("link", request.object.get("link"));
    question.save().then((question) => {
            // Execute any logic that should take place after the object is saved.
            console.log('New object created with objectId: ' + question.id);
        }, (error) => {
            // Execute any logic that should take place if the save fails.
            // error is a Moralis.Error with an error code and message.
            console.log('Failed to create new object, with error code: ' + error.message);
        });
    }

});


Moralis.Cloud.afterSave("TipCreated", async function(request) {
    const query = new Moralis.Query("QuestionTipsSum");
    query.equalTo("questionId", request.object.get("questionId"));
    const results = await query.find();
    console.log(results)
    const question = results[0];

    //Updathe the value of this question and save
    // couldnt find any examples to that

  });

The fist cloud function works fine and created a new collection QuestionTipsSum
But I dont know how to get the second function working. Please help.

https://docs.moralis.io/moralis-server/database/objects#saving-objects

the syntax is with .set and .save

The second cloudFunction doesnt even get called (The one on TipCreated Table). I dont know what the error is:

Moralis.Cloud.afterSave("QuestionCreated", async function(request) {
    const confirmed = request.object.get("confirmed");
    console.log(request.object);
    if (confirmed) {
        const array = [number];

        const Question = Moralis.Object.extend("QuestionTipsSum");
        const question = new Question();
        question.set("questionId", request.object.get("questionId"));
        question.set("sessionId", request.object.get("sessionId"));
        question.set("value", parseInt(request.object.get("value")));
        question.set("createdBy", request.object.get("createdBy"));
        question.set("createdAt", request.object.get("createdAt"));
        question.set("link", request.object.get("link"));
        question.set("tipIds", array);
        question.save().then((question) => {
                // Execute any logic that should take place after the object is saved.
            console.log('New object created with objectId: ' + question.id);
        }, (error) => {
            // Execute any logic that should take place if the save fails.
            // error is a Moralis.Error with an error code and message.
            console.log('Failed to create new object, with error code: ' + error.message);
        });
    }

});


Moralis.Cloud.afterSave("TipCreated", async function(request) {
    const query = new Moralis.Query("QuestionTipsSum");
    query.equalTo("questionId", request.object.get("questionId"));
    query.find({
        success:function(list) {
            let question = list[0];
            let oldValue = question.get("value");
            let tipIds = question.get("tipsIds");
            console.log("old Value", oldValue);
            let newValue= oldValue + parseInt(request.object.get("value"));
            tipIds.push(request.object.get("tipId"));
            question.set("value", newValue);
            question.set("tipIds", tipIds);
            question.save().then((question) => {
                // Execute any logic that should take place after the object is saved.
            console.log('New object created with objectId: ' + question.id);
        }, (error) => {
            // Execute any logic that should take place if the save fails.
            // error is a Moralis.Error with an error code and message.
            console.log('Failed to create new object, with error code: ' + error.message);
        });
        }
      });
  });

how do you know that it doesn’t get called?

did you add some logger.info lines there?
were rows added or edited in that TipCreated table?

I have changed this:


Moralis.Cloud.afterSave("TipCreated", async function(request) {
    logger.info(`New TIP with Question id ${request.object.get("questionId")}` );
     logger.info(`New tip with tipId ${request.object.get("tipId")}` )
     const Question = Moralis.Object.extend("QuestionTipsSum");
     const query = new Moralis.Query(Question);

      query.get(request.object.get("questionId"))
        .then((question) => {
            let oldValue = question.get("value");
            let tipIds = question.get("tipsIds");
            console.log("old Value", oldValue);
            let newValue= oldValue + parseInt(request.object.get("value"));
            tipIds.push(request.object.get("tipId"));
            question.set("value", newValue);
            question.set("tipIds", tipIds);
            question.save().then((question) => {
                        // Execute any logic that should take place after the object is saved.
                            logger.info('New object created with objectId: ' + question.id);
                        }, (error) => {
                        logger.info('Failed to create new object, with error code: ' + error.message);
                });
        }, (error) => {     
            logger.info(`QuestionId couldnt be found ${request.object.get("questionId")}` )

        });

});

Now the QuestionTipsSum does have a row with questionId = 0xd64f74672cc971056d6e59667ac467b643a0872c6d84b50f02e2975b26cdff05

but the error i am getting in Logs is this:

QuestionId couldnt be found 0xd64f74672cc971056d6e59667ac467b643a0872c6d84b50f02e2975b26cdff05

thanks for getting back
you are posting too much code it’s difficult to help

isolate the issue into 1-2 lines of code we can help with

you need to do some debugging work yourself and find the exact 1-2 lines that dont work and try to understand why

Repasting

Now the QuestionTipsSum does have a row with questionId = 0xd64f74672cc971056d6e59667ac467b643a0872c6d84b50f02e2975b26cdff05

but the error i am getting in Logs is this:

QuestionId couldnt be found 0xd64f74672cc971056d6e59667ac467b643a0872c6d84b50f02e2975b26cdff05

I just got to know that too much code makes debugging difficult.

That’s not Moralis error
it’s your error because query.get fails - it can fail for different reason, you can try to print out the error

my advice:

  1. remove all your code
  2. do 1 line at a time and ensure it works

you will find the issue if you test one step at a time

you have some logic issue in your code and you have to debug it step by step

it seems like you are using Query completely wrong
please read the docs https://docs.moralis.io/moralis-server/database/queries#basic-queries

if you want to find data based on a query you need to construct it and then run query.find()

Like the docs show - if you want to find data based on a column - you construct a query using equalTo and then run query.find()

you need to learn some basics - then redo your code from scratch

good luck :raised_hands:

Yes .Sorry for bugging you unnecessarily.
I got it working , Thanks for all the Help @ivan @cryptokid

1 Like