Discovering nested documents in MongoDB using JavaScript

How to find nested data in MongoDB with the following collection:

{
 "_id": {
  "$oid": "585b998297f53460d5f760e6"
 },
 "newspaper": {
  "playerID": "57bffe76b6a70d6e2a3855b7",
  "playerUsername": "dennis",
  "player_newspaper": "{\"ID\":\"57bffe76b6a70d6e2a3855b7\",\"Username\":\"Dennis\",\"itemName\":\"Corn\",\"Comment\":\"Jagung Promo\",\"Date\":\"12/27/2016\"}"
 }
}

Here is my code:

var datex = new Date();
var dates = datex.getMonth() + '/' + datex.getDate() + '/' + datex.getFullYear();
db.playerNewspaper.remove( {"newspaper.player_newspaper.Date": dates } ) ;

The above code snippet is not working as expected.

In order to insert data, I use the following method:

var currentPlayer = {
        "playerID": playerID,
        "playerUsername": playerUsername,
        "player_newspaper": newspaper

    }; // A new player object is created using the input data

    playerDataList.insert(
    {
      "newspaper" : currentPlayer
    } // Updating old player data with current player data using the $set mongo modifier
    );

Answer №1

Your query seems correct, but the issue lies within your data. In your query condition, you are assuming that player_newspaper is an object, however, the data displayed shows that player_newspaper is actually a String. This discrepancy is causing the query "

"newspaper.player_newspaper.Date": date
" to not locate any documents, resulting in the query not functioning as expected.

The structure of your document should resemble the following:

{
    "_id" : ObjectId("585b998297f53460d5f760e6"),
    "newspaper" : {
        "playerID" : "57bffe76b6a70d6e2a3855b7",
        "playerUsername" : "dennis",
        "player_newspaper" : {
            "ID" : "57bffe76b6a70d6e2a3855b7",
            "Username" : "Dennis",
            "itemName" : "Corn",
            "Comment" : "Jagung Promo",
            "Date" : "12/27/2016"
        }
    }
}

By adjusting your document structure accordingly, your query should function properly.

var datex = new Date();
var dates = datex.getMonth() + '/' + datex.getDate() + '/' + datex.getFullYear();
db.playerNewspaper.remove( {"newspaper.player_newspaper.Date": dates } } } ) ;

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

Submitting a form is disabled when there are multiple React form inputs

I have a simple code example that is working correctly as expected. You can check it out here: https://jsfiddle.net/x1suxu9h/ var Hello = React.createClass({ getInitialState: function() { return { msg: '' } }, onSubmit: function(e) { ...

Integrating individual script into HTML

Imagine you have a file named public/index.html. Additionally, there is another html file called otherScript, which contains only <script> tags with a script inside. How can you include these scripts into your public/index.html file? You intend to ...

A method for categorizing every tier of JSON data based on a shared attribute

I am encountering issues with my project as I attempt to construct a tree using JSON data. Here is an example of what I have: var treeData = [ { "name": "Root Node", "parent": "null", "children": [ ...

Terminal throws an error stating that no default engine was specified and no extension was provided

I have been working on executing a backend program in Node.js using MongoDB. I have created a form with two input fields for password and name. I am not utilizing any HBS or EJS and my VS Code terminal is displaying the following error: No default engine ...

The JS Uri request is being mishandled

My current challenge involves POSTing to a server using Request JS, specifically with some difficulties related to the path. return await request.get({ method: 'POST', uri: `${domain}/info/test/`, body: bodyAsString, head ...

Jade File Rendering Issue Detected

I am encountering an issue when trying to render the Jade file. Here is the code I have in app.js: app.get('/photos/new' function(req, res) { res.render('/photos/new', { locals: { photo: new Photo() } ...

Is it possible to configure MongoDB to function with Vercel's Edge Serverless Functions?

My API on Vercel Serverless Functions is causing long cold start times when creating new documents. In order to improve request speed, I'm considering running the API on Vercel Edge Functions. However, I have encountered an issue as the edge runtime d ...

Looking to incorporate jQuery Form Wizard with mandatory radio button groups?

Currently, I am utilizing the jQuery Form Wizard plugin from The Code Mine website to transform a form into a wizard format. Myform consists of five pages, each containing approximately four radio buttons. It is crucial that at least one radio button on ea ...

Enable the jQuery UI Autocomplete feature with Google Places API to require selection and automatically clear the original input field when navigating with the

I am currently using a jquery ui autocomplete feature to fetch data from Google Places... The issue I am experiencing is that when the user navigates through the suggestions using the up and down arrows, the original input also appears at the end. I would ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

Encountering difficulties parsing XML using NodeJS (with ExpressJS) for MongoDB integration

I have a unique scenario where my data source is only available in XML format, whereas MongoDB prefers JSON. To work around this, I am attempting to adapt a method that currently handles JSON data to now process XML data instead. Below is the modified met ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Next.js is unable to identify custom npm package

My unique custom package structure looks like this: package.json Posts.js Inside Posts.js, I have the following code: const Posts = () => { return <div>List of posts</div> } export default Posts; After publishing to the GitHub Package ...

How can I adjust the scale and position of my image textures in Three.js?

Is there a way to adjust the scale and position of my image textures? The dimensions of my image are 1024px x 1024px. let textureMap = THREE.ImageUtils.loadTexture( 'texture.png' ); https://i.sstatic.net/wKd6f.jpg ...

I am encountering an issue where my React application is unable to establish a connection with my Express application when I dockerize them together. Can anyone

Currently tackling a project for my university that involves using a react app for frontend, an express app for backend, and mongodb as the database. Previously, I would launch the express app and react app separately before dockerizing them, and everythin ...

There seems to be an issue with .ENV functionality in Razzle JS

Attempting to deploy a Razzle project on an Ubuntu server has been challenging. I have created a .env file with two variables: port=80 and host=192.168.1.5. However, when running the project, it defaults to localhost:3000. I've tried exporting PORT=80 ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...

Guide on authenticating and validating login and registration forms using Angular 8

In my application, I have successfully implemented a login and registration form. However, the backend validation for error messages like "User already exists" and "User does not exist" is not working as expected. I am unsure of how to proceed with impleme ...

What is the reason behind the jQuery JSON parser requiring double escaping for backslashes?

I'm struggling to comprehend a strange aspect of the JSON data format. Here's the issue: I have a string with a Windows directory path, where backslashes are escaped. However, the jQuery JSON parser seems to require double escaping for some reas ...

Error: The if statement is not providing a valid output

I am currently developing a basic price calculator that calculates the total area based on user input fields. While most of the program is functioning correctly, I am encountering an issue with the if statement that is supposed to determine the price rat ...