What steps can be taken to stop the update function from inserting data into MongoDB from a Meteor application

Within my Meteor method, I have implemented a function to check for existing documents. If the document is not found, it gets inserted into the database. However, if it is found during a second attempt, the document is updated and a new one is also inserted. Could you please review and help me fix the code below:


'upload': function upload(data, name, eventId) {
    const wb = XLSX.read(data, {type:'binary'});
    var checkUpdate;
    XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]).forEach(r => {
        r.owner = this.userId,
        r.username = Meteor.user().username,
        r.updatedAt = new Date(),
        r.amount = Number(r.amount),
        r.eventid = eventId,
        r.firstname = r.firstname.trim(),
        r.lastname = r.lastname.trim(),
        Registers.findOne({ firstname: r.firstname, lastname: r.lastname, eventid: eventId }) ? 
        Registers.update({ firstname: r.firstname, lastname: r.lastname, eventid: eventId }, { $set: {updatedAt: r.updatedAt, amount: r.amount } })
        : 
        r.createdAt = new Date(),
        Registers.insert(r)
    })

    return wb;
},

When the database is empty for the first time, a new document is inserted. On the second attempt, if a matching document is found, it gets updated, and a new document is inserted using the update operation instead of insertion.


meteor:PRIMARY> db.registers.find({ eventid: "aZrumf45q8sBGGrY2" })
{ "_id" : "MzqD73vsgyxRTyekJ", "salution" : "Mr.", "firstname" : "qwer", "lastname" : "asdf", ...
...

After running the code twice, I noticed that the 'createdAt' field was lost during the second instance. Can anyone explain why this happened?

I have figured it out now! Thank you so much for all your comments!


'upload': function upload(data, name, eventId) {
    const wb = XLSX.read(data, {type:'binary'});
    var checkUpdate;
    XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]).forEach(r => {
        if (!Registers.findOne({ firstname: r.firstname, lastname: r.lastname, eventid: eventId })) {
        r.owner = this.userId,
        r.username = Meteor.user().username,
        r.updatedAt = new Date(),
        r.amount = Number(r.amount),
        r.eventid = eventId,
        r.firstname = r.firstname.trim(),
        r.lastname = r.lastname.trim(),
        r.createdAt = new Date(),
        Registers.insert(r)
        } else {
        r.owner = this.userId,
        r.username = Meteor.user().username,
        r.updatedAt = new Date(),
        r.amount = Number(r.amount),
        r.eventid = eventId,
        r.firstname = r.firstname.trim(),
        r.lastname = r.lastname.trim(),
        Registers.update({ firstname: r.firstname, lastname: r.lastname, eventid: eventId }, { $set: {updatedAt: r.updatedAt, amount: r.amount } })
        }
    })
    return wb;
},

Answer №1

If you are in search of the Collection.upsert method, look no further.

This function essentially updates one or more documents in the collection, or inserts a new document if there are no matches found. It returns an object with keys numberAffected (indicating the count of modified documents) and insertedId (representing the unique _id of the newly inserted document, if applicable).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

Encountering a 500 internal server error after deploying due to utilizing getServerSideProps in Next.js

When trying to redeploy my website on Vercel, I added getServerSideProps to my index.js file. However, I encountered an error that I am not familiar with. The program works perfectly on localhost. This is the getServerSideProps code that I added: export a ...

Can the mDNS string received through webRTC be decoded to retrieve a user's IP address?

After doing some thorough research, I came across this insightful response from a different Stack Overflow question. The problem at hand involves retrieving an mDNS string, which looks like this: abcd1234-1e1e-1e1e-1e1e-abcd1a2bc3de.local I have a genuin ...

Retrieve the HTML value of an element in Vue.js by clicking on its adjacent element

Hey there, I'm currently working on a simple notes app and I've hit a roadblock with one particular feature. In my project, I have a card element with a delete button as a child. What I need to achieve is to check if the value of the .card-title ...

Is innerHTML incapable of executing JavaScript code?

Experimenting with a new technique where I divide my code into separate files to create multiple HTML pages instead of one large one. Using ajax to load them and then setting the content as innerHTML to a parent div results in clean code that works well in ...

Incorporate titles for items in the jquery caroufredsel plugin

I am currently using the second example of the caroufredsel plugin, which can be found on this page . I am attempting to add a caption for each picture. To achieve this, I have used `li` and `lis` in my HTML code: <div class="list_carousel"> &l ...

jQuery function for shuffling the order of a random div?

Upon loading the page, I have implemented a code that randomizes the order of the child divs. Here is the code snippet: function reorder() { var grp = $("#team-posts").children(); var cnt = grp.length; var temp, x; for (var i = 0; i < cnt; ...

Angular2 - receiving an error message stating that this.router.navigate does not exist as a

Currently, I am delving into the world of Angular2 with Ionic and working on crafting a login page. However, upon loading the page, an error surfaces: 'router.initialNavigation is not a function' To address this issue, I inserted '{initialN ...

Receiving a response from an XMLHttpRequest() within a function

I've come across a situation where I have a function called isOnline(), and here's how it looks: function isOnline() { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(request.readyState==4) { ...

The attribute 'subtle' is not found within the definition of 'webcrypto' type

Currently, I am working with Node v17.4 and I am looking to utilize the webcrypto API. Referencing this specific example, I am attempting to include subtle in my project, but TypeScript is throwing an error: Property 'subtle' does not exist on ...

Guide to switching classes with jquery

On my webpage, I have a star rating system that I want to toggle between "fa fa-star" and "fa fa-star checked" classes. I found some information on how to do this here: Javascript/Jquery to change class onclick? However, when I tried to implement it, it di ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

Troubleshooting Problem with Angular JS Page Loading on Internet Explorer 9

My angularjs single page application is encountering issues specifically in IE9, despite functioning perfectly in Chrome and Firefox. The initial load involves downloading a substantial amount of data and managing numerous dependencies through requireJS. ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

Convert ViewBag into a JSON array in order to create a bar chart in a .NET MVC application

I am struggling to convert ViewBag into a Json array in order to create a chart within the .Net MVC framework. Despite attempting to parse the Json data based on solutions from previous queries, the chart is not displaying anything. Here is my code: Contr ...

Navigating the world of date pickers: a deceptively easy challenge

Take a look at this fiddle example to get started: http://jsfiddle.net/1ezos4ho/8/ The main goals are: When a date is selected, it should be dynamically added as the input value, like <input type text value="date selected".... Update: <s ...

Whenever I press a button, my desire is for each picture to seamlessly reposition itself in the exact same spot on the screen

Having some issues with my code. When I click a button, the plan is for the pictures to change one by one to simulate a traffic light sequence. However, when I run the code, all the pictures appear at once without any effect from the button. Any help in ac ...

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

Emphasize a specific line of text within a <div> with a highlighting effect

I'm looking to achieve a similar effect as demonstrated in this fiddle As per StackOverflow guidelines, I understand that when linking to jsfiddle.net, it's required to provide some code. Below is the main function from the mentioned link, but f ...