What is causing the while loop in Mongodb to repetitively insert the same document rather than cycling through the documents?

Currently, I am in the process of redesigning a MongoDB database structure where the reviews for a specific product will be integrated into the product document itself, rather than maintaining separate collections for products and reviews. I have created a loop that goes through each review and inserts it into the corresponding product document. However, upon querying the database later on, I have noticed that if a product has multiple reviews, the first review is duplicated for each review present.

Any assistance or guidance on this matter would be greatly appreciated.

Here are examples of the product and review documents prior to the update:

// Product Document
{
    "_id" : ObjectId("5d0b6d1cd7367de7f58b4a77"),
    "p2507945_asin" : "B00005JHK9",
    ...
}

// Review Documents for Product
{
    "_id" : ObjectId("5d0b70f2d7367de7f5fa1da3"),
    ...
}
...

Snippet of the code used for the update:

var RvColcursor = db.p250794_reviews.find({}, {_id : 0});
...

An example of the returned output:

{
    "_id" : ObjectId("5d0b6d1cd7367de7f58b4a77"),
    "p2507945_asin" : "B00005JHK9",
    ...
}

Answer №1

There seems to be a logic error present in the code snippet.

This piece of code allows you to access every document within the p250794_reviews collection

var RvColcursor =
db.p250794_reviews.find({}, {_id : 0});

Here, the cursor is looped through to fetch the productId from each document

while (RvColcursor.hasNext()) {
  var nextRVDoc = RvColcursor.next();
  var ProductID = nextRVDoc.p2507945_asin;

Another query is made to retrieve the first review for the specific ProductId from the p250794_reviews collection

  var RvDoccursor = db.p2507945_reviews.find({p2507945_asin : ProductID}, {_id : 0, p2507945_asin : 0});
  var nextRVDocUp = RvDoccursor.next();

This retrieved review is then added to the reviews array

  db.p2507945_products.update({p2507945_asin : ProductID}, {$push : {Reviews : nextRVDocUp}});
}

However, it seems like the code is neglecting the reviews obtained from the cursor and instead repeatedly fetching and inserting only the initial review for each document.

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

Collaborate on global functions across the Quasar ecosystem and beyond, including Vue3

Is it plausible to utilize this method for sharing functionality (not data, which is handled by stores) in a Quasar and Vue3 application? // boot/generic_stuff.js import {boot} from 'quasar/wrappers' const function_list = { /* content goes here ...

Using Node.js Express to transfer data to and from MongoDB

I needed to safeguard my server data without a backup, so I decided to export it to my local machine. Using MongoDB and Node Express, I wrote the following code to extract the collection in JSON format and save it locally. Now that I have the JSON file, I ...

Prevent redirection on buttons within ionic lists

THE ISSUE: I am facing an issue in my Ionic app where I am using the ion-list component. Each item in the list can be swiped to reveal a button (add/remove to favorites). Additionally, each item serves as a link to another page. The problem arises when ...

Experiencing peculiar behavior with the delete keyword in JavaScript

Okay, so here's the deal... var obj = people[0]; obj.oAuthID = null; delete obj.oAuthID; This code snippet returns... { "uuid": "39b2b45f-1dde-4c9a-8765-1bc76f55848f", "oAuthID": null, "date": "2013-10-21T16:48:47.079Z", "updated": "2013-10 ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...

Unusual behavior observed during the selection of a random number within a specified range

When a user inputs a range, let's say 3-5, the script should generate a random integer within that range. Initially, the code functions correctly. length = Math.floor(Math.random() * (5 - 3 + 1)) + 3; However, when I try to extract the values progra ...

The custom pagination feature in Addsearch UI always default to displaying the first page of search

I am currently using addsearch-ui version 0.7.11 for my project. I have been attempting to integrate a customized pagination function based on this example template. However, I have encountered an issue where the arrow buttons always navigate to the first ...

Sending numerous messages from a single event using Socket.io

After an exhaustive search, I have yet to find a solution to my problem. I am attempting to send a message from the server every time it detects a file change in a specific directory. However, instead of sending just one message, it sends the same message ...

Express-Postgres encounters an issue with applying array filtering: error message indicates that the operator for comparing integer arrays and text arrays does not exist

I'm facing an issue where the same query that works on the terminal is now giving me an error: operator does not exist: integer[] && text[] It seems that pg.query is having trouble processing the expression path && Array[$1]. You can ...

Exploring the FunctionDirective in Vue3

In Vue3 Type Declaration, there is a definition for the Directive, which looks like this: export declare type Directive<T = any, V = any> = ObjectDirective<T, V> | FunctionDirective<T, V>; Most people are familiar with the ObjectDirectiv ...

What is causing the issue with mongoose populate not working when trying to populate an array?

My database setup includes 2 schemas: const mongoose = require('mongoose'); const PinSchema = new mongoose.Schema({ title: String, content: String, image: String, latitude: Number, longitude: Number, author: { type: mongoose.Sch ...

What is the process for incorporating an external script into a Vue component?

Seeking assistance urgently... I am encountering an issue with a Vue component and an endpoint that provides a script containing a small menu with actions. However, once the script is loaded, the actions do not seem to function on the page and I cannot det ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

Transform various tables enclosed in separate div elements into sortable and filterable tables

I'm encountering an issue with making multiple tables sortable and searchable on one page. Despite all the tables having the same class and ID, only the first table is responsive to sorting and searching. I've followed a tutorial that recommends ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

How can you add draggable functionality to a Bootstrap dropdown menu?

My custom bootstrap dropdown design <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span cla ...

Modifying the content of a paragraph by incorporating information from various sources

I need a way to input measurements for my items in text fields, and then with the click of a button, transfer those measurements into a paragraph in corresponding fields. The code I am currently using is shown below: <!DOCTYPE html> <html> & ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...