How to update instead of insert if entry already exists in Collection?

Hello guys!

I get data for my collection via a HTTP webhook.

I have a JS that uses the payload to insert into the collection which works fine.

However, when the same data is sent again, it gets inserted as a new entry despite setting a primary field in the collection.

So I wanted to query the collection first, if entry exists then update by the entry ID returned from the query function, else insert as new entry into the collection.

I tried the below code but it returns a HTTP 500 Internal Server when invoked as webhook.

I’m unable to move forward.

Can anyone please help.

Below is the working code that only inserts( causing duplicates)

Code:

'use strict';
import wixData from 'wix-data';
import {
    ok,
    response
} from 'wix-http-functions';
export function post_storerecords(request) {

    return request.body.json().then(body => {

                    let recUpdate = {
                        "title": body.title,
                        "location": body.location,
                        "jobType": body.jobType,
                        "positionActive": body.positionActive,
                        "requirements": body.requirements,
                        "jobDescription": body.jobDescription,
                        "responsiblities": body.responsiblities,
                        "order": body.order,
                        "jobId": body.jobId
                    };

                    return wixData.update('Jobs', recUpdate).then(result => ok({
                        body: JSON.stringify(result)
                    })).catch(err => response({
                        status: 500,
                        body: JSON.stringify(err)
                    }))      
    });
}

Below is the code that throws a HTTP 500 Error


'use strict';
import wixData from 'wix-data';
import {
    ok,
    response
} from 'wix-http-functions';
export function post_storerecords(request) {

    return request.body.json().then(body => {

        // Check if JOB ID exists
        wixData.query("Jobs")
            .eq("jobId", body.jobId)
            .find()
            .then((results) => {
                if (results.items.length > 0) {
                    // JOB ID exists - so update
                    console.log("Job ID "+body.jobId+" exists");
					
					let item = results.items[0];
					item.title = body.title; 
					item.location = body.location; 
					item.jobType = body.jobType; 
					item.positionActive = body.positionActive; 
					item.requirements = body.requirements; 
					item.jobDescription = body.jobDescription; 
					item.responsiblities = body.responsiblities; 
					item.order = body.order; 
					item.jobId = body.jobId; 
					wixData.update("Jobs", item).then(result => ok({
                        body: JSON.stringify(result)
                    })).catch(err => response({
                        status: 500,
                        body: JSON.stringify(err)
                    }));
					console.log(item);
                     //see item below

				/*
                    let recUpdate = {
                        "title": body.title,
                        "location": body.location,
                        "jobType": body.jobType,
                        "positionActive": body.positionActive,
                        "requirements": body.requirements,
                        "jobDescription": body.jobDescription,
                        "responsiblities": body.responsiblities,
                        "order": body.order,
                        "jobId": body.jobId,
                        "_id": results.items[0]._id
                    };
					
					let options = {
					  "suppressAuth": true,
					  "suppressHooks": true
					};

                    return wixData.update('Jobs', recUpdate,options).then(result => ok({
                        body: JSON.stringify(result)
                    })).catch(err => response({
                        status: 500,
                        body: JSON.stringify(err)
                    }))
					*/

                    console.log("Job ID "+results.items[0].jobId+" updated");

                } else {
                    // New Job ID - So Create
                    console.log("Job ID "+body.jobId+" does not Exist");
                    let recInsert = {
                        "title": body.title,
                        "location": body.location,
                        "jobType": body.jobType,
                        "positionActive": body.positionActive,
                        "requirements": body.requirements,
                        "jobDescription": body.jobDescription,
                        "responsiblities": body.responsiblities,
                        "order": body.order,
                        "jobId": body.jobId
                    };
                    return wixData.insert('Jobs', recInsert).then(result => ok({
                        body: JSON.stringify(result)
                    })).catch(err => response({
                        status: 500,
                        body: JSON.stringify(err)
                    }))
                    console.log("Job ID "+body.jobId+" created");
                }
            })
            .catch((err) => {
                console.log(err);
            });

    });
}

Please advise

Use wixData.save()
It either inserts or updates depends on whether or not the object _id exists in the collection

But I guess I’ll have to pass the object _id along with the save() method.

How do I get that prior to doing the save()?

Source: https://www.wix.com/velo/reference/wix-data/save

Thanks

Major update!

Insert and updates are working with the save() now!

However, the response is coming back from the API Call as 500 Internal Server Error.



Code Used:

'use strict';
import wixData from 'wix-data';
import {
    ok,
    response
} from 'wix-http-functions';

export function post_storerecords(request) {

    return request.body.json().then(body => {

        // Check if JOB ID exists
        wixData.query("Jobs")
            .eq("jobId", body.jobId)
            .find()
            .then((results) => {
                if (results.items.length > 0) {
                    // JOB ID exists - so update
                    console.log("Job ID "+body.jobId+" exists");
                    
                    let item = results.items[0];
                    item.title = body.title; 
                    item.location = body.location; 
                    item.jobType = body.jobType; 
                    item.positionActive = body.positionActive; 
                    item.requirements = body.requirements; 
                    item.jobDescription = body.jobDescription; 
                    item.responsiblities = body.responsiblities; 
                    item.order = body.order; 
                    item.jobId = body.jobId;
                    console.log(item);

                    wixData.save("Jobs", item).then(result => ok({
                        body: JSON.stringify(result)
                    })).catch(err => response({
                        status: 500,
                        body: JSON.stringify(err)
                    }));
                    console.log("Job ID "+results.items[0].jobId+" updated");

                } else {
                    // New Job ID - So Create
                    console.log("Job ID "+body.jobId+" does not Exist");
                    let recInsert = {
                        "title": body.title,
                        "location": body.location,
                        "jobType": body.jobType,
                        "positionActive": body.positionActive,
                        "requirements": body.requirements,
                        "jobDescription": body.jobDescription,
                        "responsiblities": body.responsiblities,
                        "order": body.order,
                        "jobId": body.jobId
                    };
                    return wixData.insert('Jobs', recInsert).then(result => ok({
                        body: JSON.stringify(result)
                    })).catch(err => response({
                        status: 500,
                        body: JSON.stringify(err)
                    }))
                    console.log("Job ID "+body.jobId+" created");
                }
            })
            .catch((err) => {
                console.log(err);
            });


    });
}

API Response:

Logs:

Please advise on how to return a 200 OK response structure

You need to return a http response: ok - Velo API Reference - Wix.com

Not just an object / array

Hey @saisuryachintala did you ever get this 500 error worked out? I’m facing a similar issue.