Fetching data from external sources using the MongoDB copy item function

Here is an example of an array:

"data": [
        {
            "photo": "no-photo.jpg",
            "_id": "5e9aabd9c975a10a7ee48476",
            "title": "Title",
            "description": "Description",
            "phone": "77477926783",
            "fromLocation": "5e9aa8a9c975a10a7ee48474",
            "toLocation": "5e9aa8bac975a10a7ee48475",
            "price": 1000000,
            "date": "1998-02-23T00:00:00.000Z",
            "user": "5e91729f147813258ef1f373",
            "createdAt": "2020-04-18T07:27:21.743Z",
            "__v": 0,
            "courses": [],
            "id": "5e9aabd9c975a10a7ee48476"
        }
    ]

When using for...loop:

for (const item of res.advancedResults.data) {
  console.log(item)
}

The output is standard:

{
 "photo": "no-photo.jpg",
 "_id": "5e9aabd9c975a10a7ee48476",
 "title": "Title",
 "description": "Description",
 "phone": "77477926783",
 "fromLocation": "5e9aa8a9c975a10a7ee48474",
 "toLocation": "5e9aa8bac975a10a7ee48475",
 "price": 1000000,
 "date": "1998-02-23T00:00:00.000Z",
 "user": "5e91729f147813258ef1f373",
 "createdAt": "2020-04-18T07:27:21.743Z",
 "__v": 0,
 "courses": [],
 "id": "5e9aabd9c975a10a7ee48476"
}

But when trying to copy it like this:

for (const item of res.advancedResults.data) {
  console.log({...item})
}

The output becomes:

{ '$__':
     InternalCache {...},
    isNew: false,
    errors: undefined,
    _doc:
     { photo: 'no-photo.jpg',
       ... },
    '$locals': {},
    '$$populatedVirtuals': { courses: [] },
    '$init': true } 

How can one correctly duplicate the object?

Answer №1

Whenever an operation like find, findOne, etc., is performed, Mongoose will encapsulate the result in a Mongoose model / Document with additional metadata.

Referencing the documentation here and here:

Models are specialized constructors created from Schema definitions. An instance of a model is known as a document. Models undertake the task of generating and retrieving documents from the underlying MongoDB database.

Mongoose models offer various static helper functions for CRUD operations. Each function returns a mongoose Query object.


It appears that you are attempting to extract the mongoose model similar to a regular JavaScript object.

There are two approaches to achieve this:

  1. By utilizing the { lean: true } option in your model.find() or model.findOne() methods, or using the lean() method. However, this comes with some drawbacks outlined here.

  2. Utilize the Document.prototype.toObject() method to convert the document into a plain JavaScript object.

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

Is MongoDb the right fit for my specific application needs?

Currently, I am in the process of developing an application using node.js that involves users and products in a many-to-many relationship. This means that each user can have multiple products, and vice versa. Additionally, each user also has location infor ...

Retrieve the most recent information from the API using axios and React hooks

I have access to an API that provides data, but I am only interested in the most recent information. The newest data is always located at the end of the dataset. For instance, if there are 50 points of data, the latest would be number 50. Can someone adv ...

Tips for making a sidebar sticky when scrolling

In order to keep the right-side bar fixed, I have implemented this javaScript function: <script type="text/javascript> $(document).ready(function () { var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsideb ...

Each time the page is refreshed, the objects in Three.js load in varying positions due to the OBJMTLloader

My scene is populated with various objects: var objectInfo = [ {"objURL":"3D/Barrel/barrel.obj", "mtlURL":"3D/Barrel/barrel.mtl","xPOS":0,"yPOS":-2,"zPOS":-260,"xROT":0,"yROT":0,"zROT":0,"scaleX":0.6,"scaleY":0.6,"scaleZ":0.6}, {"objURL":"3D/Sofa/sofa.obj ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Can you suggest an optimal way to structure MongoDB documents that frequently experience rapid growth in arrays?

My MongoDB document layout includes 6 top-level property fields that store array data. These arrays store IoT data collected from specific sensors throughout the day, and are updated every 2 seconds. Each new sensor packet appends data to all 6 arrays, pot ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

How can you create a dynamic bounce effect for text with jquery animate()?

I've been experimenting with Jquery to achieve a bounce effect, here's what I have so far: Html: <div id ="animation">bounce</div> Jquery: $("#animation").animate({ marginTop: "80px" }, 1500 ) .animate({ marginBotto ...

vue.js: Modifying information through watcher function

Here is the code I am currently using: export default { name: '...', props: ['user'], data() { return { userName: this.user.name } }, watch: { user: (_user) => { th ...

Application in Node.js where users are linked to diverse databases

My node.js (along with express) product administration application is currently connected to a mongodb database that houses all the product data, and utilizes Stormpath for user management. While this setup has been working well so far, I now require the ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

The noUISlider step feature does not function properly when using a multiple range option

When working on a scale from 100 to 1000, everything runs smoothly. However, once it goes beyond 1000, the step ceases to work. How can this issue be resolved? https://i.sstatic.net/FdfZT.jpg <Nouislider range={{ 'min': 100, '25%&ap ...

How can I invoke a custom function asynchronously with JavaScript?

Incorporating a specific angular third party module into my application has posed some challenges. This module offers various call-back methods such as login success and failure, where I have embedded my custom scripts for execution. However, the current ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

Receiving an 'undefined' result in an asynchronous response even with 'await' and 'then' statements implemented

I'm struggling with sending a GET request, parsing the response, and passing it to another function. It seems like I'm having difficulty dealing with the asynchronous nature of the response. I prefer to stick to using Node.js' built-in modu ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

Execute a series of Promises (or Deferreds) consecutively and have the flexibility to pause or stop at any point

Having an issue here. Need to make numerous consecutive http calls and the ability to stop the process at any point in time. The current solution I have involves jQuery and Deferreds, but it lacks proper interruption handling (still haven't transition ...

Tips for executing Cross-Origin-Requests from Firebase Hosting to an AWS Lambda function

Excuse me, I'm still new to web development. I have a basic single-page website hosted on Firebase hosting that retrieves some information from an AWS Lambda function (I didn't use Google Cloud because it didn't support outbound requests fo ...

Is it possible to change the text of a scrollspy dropdown to a default text when it is not actively tracking any items?

I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...

Encountering a "404 method not found" error in the developer console when handling meteor collections

Having an issue while trying to insert a document into my meteor collection using an autoform generated from my Mongo schema. Upon clicking the submit button, I am encountering a "method not found [404]" error in the developer console. I suspect the proble ...