Implementing a Node-RED flow to interact with MongoDB using a JavaScript object

As part of a school exercise and my personal project, I am working on setting up a NodeRed server that retrieves weather data, stores it in MongoDB, and retrieves it for future searches on the same location.

My NodeRed server is attempting to perform a replaceOne() operation on a remote MongoDB database using the "node-red-contrib-mongodb4" v 2.3.0 node. The goal is to verify if a document with matching values for city, country, and openweathermap_id exists. If it does, then replace it; otherwise, create a new document.

The issue arises when passing the object to the MongoDB node, resulting in a "MongoInvalidArgumentError: Document must be a valid JavaScript object" error. While insertOne() functions properly, replaceOne() seems to trigger this error.

For more information about the Node homepage, you can visit:

The connection configuration is not the source of the error, as other operations to the same MongoDB database work smoothly.

Despite trying various structures and methods for the object, the problem persists. Here is the most recent structure used:

The object (msg.payload) is passed to the function node.

{"city":"Happy Place","country":"Over There","weather":"Clouds","tempc":14.2,"temp_maxc":15,"temp_minc":14,"humidity":84,"pressure":1023,"windspeed":2.57,"winddirection":210,"clouds":40,"description":"The weather in Happy place at coordinates: 32.2125, 75.1209 is Clouds (scattered clouds).","openweathermap_id":111,"timestamp":"2023-08-24T15:06:09.219Z"}

Wrapping the object in an array was also attempted, which worked with insertOne() but failed with replaceOne().

Below is the code snippet from the function node leading to the MongoDB node:

msg.filter = {
    city: {$eq: msg.payload.city},
    country: {$eq: msg.payload.country},
    openweathermap_id: { $eq: msg.payload.openweathermap_id }
};
 
msg.replacement = { 
    city: msg.payload.city,
    country: msg.payload.country,
    weather: msg.payload.weather,
    tempc: msg.payload.tempc,
    temp_maxc: msg.payload.temp_maxc,
    temp_minc: msg.payload.temp_minc,
    humidity: msg.payload.humidity,
    pressure: msg.payload.pressure,
    windspeed: msg.payload.windspeed,
    winddirection: msg.payload.winddirection,
    clouds: msg.payload.clouds,
    description: msg.payload.description,
    openweathermap_id: msg.payload.openweathermap_id,
    timestamp: msg.payload.timestamp
};

msg.options = {
    upsert: true
};
return msg;

An image of the MongoDB node settings can be viewed here.

The exact reason why the object is considered invalid in JavaScript is still unclear to me.

Answer №1

It was news to me that all the CRUD values had to be contained within msg.payload as an array. I mistakenly believed only the document values needed to be.

For anyone facing a similar issue, here is the revised code:

msg.payload = [

    {city: { $eq: msg.payload.city },
    country: { $eq: msg.payload.country },
    openweathermap_id: { $eq: msg.payload.openweathermap_id }},
    {city: msg.payload.city,
    country: msg.payload.country,
    weather: msg.payload.weather,
    tempc: msg.payload.tempc,
    temp_maxc: msg.payload.temp_maxc,
    temp_minc: msg.payload.temp_minc,
    humidity: msg.payload.humidity,
    pressure: msg.payload.pressure,
    windspeed: msg.payload.windspeed,
    winddirection: msg.payload.winddirection,
    clouds: msg.payload.clouds,
    description: msg.payload.description,
    openweathermap_id: msg.payload.openweathermap_id,
    timestamp: msg.payload.timestamp},
    {upsert: true}
    ];

return msg;

Shared by question poser.

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

Get various selections from a dropdown menu in Flutter

I am currently working on a custom dropdown button and my goal is to retrieve two values when selecting an option from the list. Below is the code for the custom dropdown button: Widget customJsonDropDown(List? jsonList, String? value, void onChange(val) ...

Using the Proper 'this' Reference Without Repeating 'this' in Nested Functions

I am facing an issue in my class where I have multiple methods and properties. One of these methods contains a setTimeout() function as follows: function myClass() { this.some_property = "test"; this.PrintOnTimeout = function() { // I thou ...

The returned value is indeterminate

I have a Node.js project with a main file named index.js and a helper file named helper.js. The helper file contains some functions that are imported into the main file. I am trying to retrieve some data using a function from the helper.js file, but when I ...

What is the reason behind VueJs not having built-in support for multiple select options?

Recently delving into the world of vue, I encountered a challenge while working on an update form. When trying to pre-select multiple options using the selected attribute, I noticed that only the last option was being selected. Upon further investigation, ...

The Bootstrap toast fails to appear on the screen

I am currently working on a website project using HTML with bootstrap and javascript. I have been attempting to include a toast feature by implementing the code provided on the bootstrap website: <div class="toast" role="alert" aria-live="assertive" ...

Ajax is displaying some unusual behavior

Currently, I am working on an ajax request to check if a specific combination of username or password exists. <script> $("form").submit(function(e){ e.preventDefault(); //send data to ajax file now $.ajax({ type: 'POST ...

NewbieCoder is requesting clarification on the JQUERY smoothscrolling code, can anyone assist?

Can anyone provide an explanation of the functionality of the following JavaScript code? Specifically, I would like a breakdown of each line in this smooth scrolling API. $('a').click(function(){ //upon 'a' click, execute th ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

How can I modify the text that appears when hovering over an element?

Can the displayed text be altered on mouse hover? For instance, can I change the text of a H1 tag when hovering over it using HTML, CSS, and JavaScript? ...

Is there a way to align these side by side?

Is it a silly question? Perhaps. But I can't seem to figure out how to align my text and colorpicker on the same line instead of two. Take a look at my fiddle. I've tried removing display:block and clear:both, but that didn't do the trick. H ...

How do I capture data using an input tag in Node.js and save it in MongoDB?

I need help with inserting data from an input form and submit button into Node.js and MongoDB. Can someone provide me with tips or links on how to do this? :) <form method="post" ...> <input placeholder="Name & Surname"> <button type= ...

What do the dot and dollar sign symbolize in MongoDB?

I'm currently debugging a code that utilizes flask_pymongo and I came across the following snippet: dabb = mongo.db.tbl.find({ "transactions": {'$elemMatch': {"from":{'$elemMatch':{"from":str(to)}},"to":{'$elemMatch& ...

Storing data or a page in a list within a React Native application

As a newcomer to React Native, I'm facing an issue. I have two pages called rockSetting.js and myFavoriteSetting.js. In the rockSetting page, I want to implement an onButtonPress function that will generate a list in the myFavoriteSettings page with ...

Error: Unforeseen character 'a' found in JSON at index 2

After spending several hours attempting to fetch and exhibit JSON data externally using JSON.parse, I encountered the following error: VM935:1 Uncaught SyntaxError: Unexpected token a in JSON at position 2 at JSON.parse (<anonymous>) at Ob ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

Discover similarities between two arrays

My goal is to compare two arrays and generate a JSON array marking true if there's a match and false if there isn't. The second array will always have values that match some from the first, and it will be smaller as it's derived from the fir ...

How can I verify the presence of email and mobile numbers in my MongoDB database?

const express = require('express'); const router = express.Router(); require('../db/conn'); const User = require('../model/userSchema'); router.get('/', (req, res) => { res.send(`Hello World from the server ...

Uh-oh! Trouble loading web app dependencies: 404 Error

Currently, I have a functional SailsJS boilerplate application. The next step I am trying to undertake involves integrating Angular-Material as a dependency in order to kickstart some UI development tasks. However... After installing angular-material usin ...

Receiving Feedback from DSTK (Data Science Toolkit) using Guzzle and Goutte

I'm encountering an issue when trying to retrieve JSON data from the Data Science Toolkit. The response I receive does not contain the expected data. My attempt is to provide a string object (JSON encoded from an array of addresses) to the dstk field ...

Is incorporating RequireJS into an AngularJS project a valuable decision?

Is it true that AngularJS has its own module loading mechanism built-in and using RequireJS is unnecessary or even inefficient? I am working on an Angular project where the index.html file is becoming quite large. Would incorporating RequireJS help reduc ...