Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated!

Thank you in advance for your time.

This is what I've put together, but it's not functioning as expected:

app.post('/:collection', function(req, res) {
    var object = req.body;
    var collection = req.params.collection;
    geocoder.geocode(req.body.address.street + req.body.address.no + req.body.address.zip + req.body.address.city, function(req, res) {
    var gpslocation = ({"loc": [res[0].longitude, res[0].latitude]});
    mergedObject = JSON.parse((JSON.stringify(object) + JSON.stringify(gpslocation)).replace(/}{/g,","))
    console.log(mergedObject);
    });
    collectionDriver.save(collection, object, function(error,docs) {
          if (error) { res.send(400, error); }
          else { res.send(201, docs);} //B
   });
});

Console log shows the correct output, however, saving with longitude/latitude appended isn't working as expected:

{ cat: 'Electrician6',
name: { first: 'John', last: 'Pipe', picture_ID: '23872' },
created_at: '2015-05-16T14:05:23.431Z',
_id: '55574ea3435c2d9c24d21572',
loc: [ 4.7261822, 50.9635574 ] }

When attempting to fix it:

app.post('/:collection', function(req, res) { //A
    var object = req.body;
    var collection = req.params.collection;
    geocoder.geocode(req.body.address.street + req.body.address.no + req.body.address.zip + req.body.address.city, function(req, res) {
    var gpslocation = ({"loc": [res[0].longitude, res[0].latitude]});
    mergedObject = JSON.parse((JSON.stringify(object) + JSON.stringify(gpslocation)).replace(/}{/g,","))
    console.log(mergedObject);
    });
    collectionDriver.save(collection, mergedObject, function(error,docs) {
          if (error) { res.send(400, error); }
          else { res.send(201, docs);} //B
   });
});

Results in an error:

ReferenceError: mergedObject is not defined
    at app.put.params (/app/testapp/index.js:92:39)
    at callbacks (/app/testapp/node_modules/express/lib/router/index.js:161:37)
    at param (/app/testapp/node_modules/express/lib/router/index.js:135:11)
    at param (/app/testapp/node_modules/express/lib/router/index.js:132:11)
    at pass (/app/testapp/node_modules/express/lib/router/index.js:142:5)
    at Router._dispatch (/app/testapp/node_modules/express/lib/router/index.js:170:5)
    at Object.router (/app/testapp/node_modules/express/lib/router/index.js:33:10)
    at next (/app/testapp/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    at Object.staticMiddleware [as handle] (/app/testapp/node_modules/express/node_modules/connect/lib/middleware/static.js:55:61)
    at next (/app/testapp/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    { cat: 'Electrician6',
    name: { first: 'John', last: 'Pipe', picture_ID: '23872' },
    loc: [ 4.7261822, 50.9635574 ] }

Answer №1

Merging two objects is unnecessary in this scenario. Instead, you can simply add the "loc" property to the original object. Make sure to call collectionDriver.save within your callback function so that it only executes after geocoder.geocode is complete.

app.post('/:collection', function(req, response) {
    var object = req.body;
    var collection = req.params.collection;
    geocoder.geocode(object.address.street + object.address.no + object.address.zip + object.address.city, function(req, res) {
      object.loc = [res[0].longitude, res[0].latitude];
      console.log(object);
      collectionDriver.save(collection, object, function(error,docs) {
        if (error) { response.send(400, error); }
        else { response.send(201, docs);}
      });
    });
});

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

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

Emit a broadcast message using Socket.io, excluding the socket ID of the current user

I'm currently working on a real-time application using socket.io Every time a user accesses the application, a unique socket ID is generated. Therefore, if I open the application in multiple browser tabs, each tab will have its own socket ID. To org ...

Verification with Express Validator

I am currently using express-validator for validation purposes. At the same time, I am utilizing mongoose for database operations, which also offers built-in validation capabilities. I'm a bit confused about whether I should focus on using express-val ...

Top Tips for Effectively Scaling a Node.js App on Heroku

My website is currently hosted on the Heroku platform and we are facing significant performance issues. The setup involves a node.js/express application that serves both static HTML (using AngularJS) and REST APIs for client consumption. With deployment ...

A guide on transferring data to an external JavaScript script that is asynchronously loaded

I came across this solution on Stack Overflow here to load JavaScript asynchronously. However, I am wondering how can I pass some data to the external file? This is my current code: <script id="js-widget-o2ba1y" type='text/javascript'> ...

What is the process for setting up redux in _app.tsx?

Each time I compile my application, I encounter the following error message: /!\ You are using legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). Although my application functions correctly, I am unsure ...

Is it possible to execute a REST call in JavaScript without utilizing JSON?

(I must confess, this question may show my lack of knowledge) I have a basic webpage that consists of a button and a label. My goal is to trigger a REST call to a different domain when the button is clicked (cross-domain, I am aware) and then display the ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Check for a rapid return if the function ends up returning null in JavaScript

Is there a way to make this code more concise? const result = getResult(); if (!result) { return; } // Work with result I have several instances of this code in my project and I'm looking for a simpler solution like: const result = getResult() ...

Why is my host address not being recognized by nodejs v5.10.1 anymore?

Why is the latest version of Node.js (v5.10.1) no longer able to retrieve my host address? Here's the Express code snippet: var express = require('express'); var app = express(); // Respond with "Hello World!" on the homepage app.get(&apo ...

JavaScript: What is the concept of overriding function named params?

function retrieveData({item1 = "blue", item2 = 7}) { console.log('theItems'); console.log(item1); console.log(item2); } retrieveData( { item1: 'pink', item2: 9 } ); I've come across conflicting i ...

Troubleshooting: Why are my images not displaying in webpack and node.js setup?

My problem: I'm facing an issue with background images in my project. I have included two images and used file-loader to bundle them through webpack. While the images display correctly in the app during development using webpack-dev-server, they disap ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

Encountering an issue preventing the installation of node-gyp

I am facing difficulties installing node-gyp on Windows 7. Despite extensive research and trying various suggestions, I attempted using (+) to run npm install no-gyp-xml-stream. However, when running cmd as administrator, the following errors occurred: gy ...

Transforming the breakpoint can cause fluctuations in the jQuery UI selectable selected event

I'm running into an issue with a jQuery UI selectable div that contains child divs. The problem is that the child divs are not getting selected until I insert a breakpoint inside the selected handler. For a live example, please see my JS Fiddle: htt ...

Customize AngularJS checkbox values when checked

Is there a way to set a checkbox to be checked by default with a custom value instead of a boolean value? Ready to go? <input type="checkbox" ng-model="checked" ng-init="checked=true" ng-true-value="sure" ng-false-value="nope"><br/> <tt> ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

The previous successful execution of req.body is now yielding an undefined value

My req.body is suddenly undefined, even though it was working fine a few days ago. I've tried using the deprecated body-parser module, but no luck. Here's my code: JS: var express = require("express"); var router = express(); require(& ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...