Storing intricate information in MongoDB

I've been exploring the JSON-BSON structures of MongoDB, but I'm struggling to understand how to insert documents into other documents and query them.

Here's what I'm curious about - let's say someone wants to store an array of documents within another array, like in a school:

  const university = mongoose.Schema(
  {
     name : {type : String, require : true, unique : true},
     school : [{
        schoolName : String
    }]
  });

Could someone explain how to insert documents within an array of documents based on the name? I'm new to MongoDB and would appreciate any guidance.

Answer №1

To add data:

const School = mongoose.model('school')
const school = new School({
  name: 'Yale',
  programs: [
    {name: 'Art'},
    {name: 'Science'}
  ]
})
school.save(function (err, school) {
  console.log(school)
})

To search within an array:

const School = mongoose.model('school')

// To find an item in the array
School.find({ 'programs.name': 'Art' }, function (err, schools) {
  console.log(schools)
})

// To find an item at a specific index
School.find({ 'programs.0.name': 'Art' }, function (err, schools) {
  console.log(schools)
})

To add an element to the array:

You can achieve this by using the $push operator which appends a value to an array.

const School = mongoose.model('school')
School.update(
  { name, 'Yale' },
  {
    $push: {
      programs: {name: 'Music'}
    }
  },
  function (err, schools) {}
)

Feel free to visit for various courses that are both informative and free of charge.

Additionally, exploring the documentation for mongodb and mongoose can greatly enhance your understanding.

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

Transfer information from a Vue function to an external JSON document

I would like to store the data for my Vue project in an external JSON file instead of within the Vue function itself. I attempted to retrieve data from an external file using the code below, but encountered issues, possibly due to a conflict with the "ite ...

Warning: Mongoose Server Selection Error - Unhandled Rejection Promise Detected

What is the cause of the UnhandledPromiseRejectionWarning: MongooseServerSelectionError Bug?* What is happening currently? I am attempting to connect mongoose with a URL string, everything seems correct. However, after executing console.log("mongoDB data ...

Encountered an issue retrieving audio during recording with Recorder.js

I've come across a scenario where I'm utilizing the Recorder.js Demo for recording audio. Interestingly, it works perfectly on Linux but encounters an issue when used on Windows. A pop-up alert stating "Error getting audio" shows up. Here's ...

Creating a Python web scraper that utilizes Selenium and PhantomJS to extract DOM information

Attempting to extract data from a website that uses JavaScript to build the DOM, I employed both Selenium and PhantomJS. While the code provided below sometimes works, it often retrieves an empty website without executing the necessary JavaScript. Only oc ...

What causes an error when trying to access with the member access operator?

When dealing with object properties in the code snippet below, an error is thrown when trying to access the object using the Member Access. Why does this happen? var d = {a: 10, b: 20, c:30}; var keys = Object.getOwnPropertyNames(d); ...

Linking input to radio buttons in Vue.js

When creating an edit form page, I encountered an issue where the page was not loading properly. Before the page loaded, I ran the following code: beforeMount(){ if(this.$route.meta.mode === 'edit'){ this.initialize = '/api/arti ...

Obtaining serverTime from a webpageWould you like to learn

Is it possible to retrieve the serverTime using jquery ajax functions like $.get() or $.post()? I am looking to store this serverTime in a variable that can be utilized later on in javascript. You can access the webpage at: To use the get and post functi ...

"Although the query functions properly on its own, MongoDB is unexpectedly returning a null value

Within a post function, my aim is to fetch the nth activity of a user by using a dropdown menu that provides the index number. The query I am running looks like this: collection.find({'local.email':req.user.local.email}, {'local.acti ...

What are the steps to recursively transform a JavaScript object?

I am currently working on recursively transforming a JavaScript object, but I have encountered an issue. The problem is: if any object key has exactly two properties - 'label' and 'value', then the value should change to the label only ...

AngularJS ng-repeat items do not properly align when utilizing Bootstrap col-md-2 styles

Utilizing AngularJS ng-repeat for displaying a list of products and incorporating bootstrap col-md-2 to showcase 6 products in each row, I have included a condensed version of my code below: <!DOCTYPE html> <html lang="en"> <head> <ti ...

Is an Ajax powered loading feature used in transitions between pages?

I recently came across this interesting website: It appears that they have implemented a clever technique where new content is dynamically loaded using AJAX, giving the impression of seamless navigation. Additionally, they have succeeded in hiding the bro ...

Parent window encountering issue while calling child window function

Recently, I have been encountering issues with using an iframe inside a thickbox and calling the function within the iframe. The code snippet I'm currently using is window.frames[0].test();, which seems to be working inconsistently across different br ...

What methods can I use to adjust link distance while using the 3d-force-graph tool?

Exploring the capabilities of the 3D Force Graph from this repository has been an interesting journey for me. I am currently seeking ways to adjust the bond strength between nodes. I am specifically looking to modify either the link width or length, but ...

javascript change string into an array of objects

let dataString = "{lat: -31.563910, lng: 147.154312};{lat: -33.718234, lng: 150.363181};{lat: -33.727111, lng: 150.371124}"; let dataArray = dataString.split(';'); Produces the following output: let dataArray = [ "{lat: -31.563910, lng: 147 ...

Transmit JSON data from the client to the MarkLogic Server device

Hello everyone, hope you are all doing well. I am a beginner in Marklogic and recently managed to set up a rest api on my local machine. Following the given example, I used curl to send/create documents in the database. Now, my query is how can I access/ ...

What are the ideal situations for utilizing embedded documents within MongoDB?

I have been researching about embedding in MongoDB extensively, but I am still uncertain on when it should be used. To help clarify, let's consider a few scenarios: Imagine we have a collection called UserGroups with fields like: _id name Now, if ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

Tips on how to use console.log in react-simple-chatbot

I am currently working on a chatbot project and would like to add some features such as sending emails and popups. However, I am facing an issue with console logging elements in my code. Here is the snippet of my code: import React from "react"; ...

The API response in JSON format is displaying as "undefined"

My current code is running as follows: const request = require('request') const apiKey = 'XXXXXXXXXXXXXX' var dat; let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx' let qs = { q: '-34.48,150.92&ap ...

Using the timer function to extract data within a specific time frame - a step-by-step guide

Is there anything else I need to consider when the temperature increases by 1 degree? My plan is to extract data from my machine for the last 30 seconds and then send it to my database. set interval(function x(){ If(current_temp != prev_temp){ if((c ...