Updating an array of numbers in Mongoose: A guide

I am having trouble updating an array within a MongoDB document using Mongoose. Below is my stock model definition:

const ticker = new mongoose.Schema({
   ticker: String,
   Price: Number,
   Amount: Number,
   PastPrices: [Number]
});
export const stock = mongoose.model("Stocks", ticker);

Here is an example document in MongoDB:

{
  "_id": {
    "$oid": "61e5d0e1dfda4d7c85dc8fe2"
  },
  "PastPrices": [
    2
  ],
  "ticker": "TSLA",
  "Price": 2,
  "Amount": 0,
  "__v": 0
}

Despite running the update operation with Mongoose, the PastPrices array is not being updated as expected. My goal is to continuously add values to this array every few seconds and eventually display them on a chart.

 stock.updateOne({ticker: "TSLA"},
        { $push: { PastPrices:1}}
    );

No error messages are being displayed, but the array is simply not updating as intended.

Answer №1

updateOne function doesn't immediately execute the update operation, instead it returns a Query object. The Mongoose Queries guide explains this concept:

You can execute a mongoose query in two ways. Firstly, by passing a callback function to Mongoose, the query will be executed asynchronously and the results will be passed to the callback function.

Additionally, a query has a .then() function and can be treated as a Promise.

This means that you can pass a callback function as shown in the query execution documentation:

const Person = mongoose.model('Person', yourSchema);
// Find a person with last name 'Ghost' and retrieve `name` and `occupation`
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
 if (err) return handleError(err);
 // Output: "Space Ghost is a talk show host"
  console.log('%s %s is a %s.', person.name.first, person.name.last,
    person.occupation);
});

You also have the option to use then() or exec() for handling Promises. As mentioned in the Mongoose promise documentation:

const query = Band.findOne({name: "Guns N' Roses"});
assert.ok(!(query instanceof Promise));

 // A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function(doc) {
 // do something with doc
});

// Using `.exec()` provides a complete promise
const promise = Band.findOne({name: "Guns N' Roses"}).exec();
assert.ok(promise instanceof Promise);

promise.then(function (doc) {
  // handle doc
});

If you are in an async context, you can utilize await on the query:

await stock.updateOne({ticker: "TSLA"},
        { $push: { PastPrices:1}}
    );

Answer №2

Your inquiry is accurate, however, to ensure that the query fetches updated data, you must include an additional configuration { new: true }. Omitting this may result in the query updating the data but returning outdated information.

stock.updateOne(
  { ticker: "TSLA" },
  { $push: { PastPrices:1 } },
  { new: true }
);

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 it possible for me to add a string to a URL as long as the string is not null?

When retrieving data from a database, I have the option to include specific parts for a more targeted search. Let's say I have an object structured like this: { title: "wonderland", aliases: "", ... } My goal now is to generate a URL for the ...

What is the process for reporting a security vulnerability in an npm package if you are the maintainer and publisher?

If I discover a security flaw in my published packages, how can I indicate which versions are vulnerable so that users running `npm audit` will be alerted? ...

Having images that are too large in size and using a high percentage can

I'm encountering a strange issue. When I define the width and height of my images in pixels in my CSS file, all my jQuery animations and events work perfectly fine. However, when I switch to using percentages or 'auto' for the image dimensio ...

Difficulty in aligning the text of the ListItem

I am working with a material-ui list that looks like this: <List dense> {this.state.issues.map((item, i) => { return <Link target="_blank" to={item.issue_url} key={i}> <ListItem button> <ListItemText primary={item.i ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

Converting a Symfony2 DateTime object from MongoDB: a step-by-step guide

Hello, I am currently working on developing a reminder section for my application where I need to check multiple dates. However, when I retrieve dates from the mongodb database, I encounter the following structure: DateTime Object ( [date] => 2014 ...

Changing the style of characters within a contenteditable element

Seeking advice on how to implement an input element that changes style (like font color) between two specific characters (such as '[' and ']'). I'm considering using a contenteditable div but open to other suggestions. Currently ex ...

How do I retrieve unique values for a field while applying other conditions in pymongo queries?

Looking to retrieve distinct values for a specific field using pymongo while also being able to pass additional query parameters. For instance, considering entries like: { id = "my_id1" tags: [tag1, tag2, tag3], category: "movie", } { id = "my ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Selecting keys of an object in Angular 2

Attempting to fetch data from an API using key selection but encountering retrieval issues. File: app/app.component.ts import {Component, OnInit} from 'angular2/core'; import {Http} from 'angular2/http'; import {httpServiceClass} fro ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

Decimal tally in React using JavaScript

I'm struggling with my counter code that is supposed to count from 0 up to a given number, but it seems to have issues with decimals. For example, if it's set to count to 4.5, it stops at 4.1 or when counting from 0 to 5.7, it stops at 5.1. I&apo ...

Persisting a modal in NextJS on page refresh - navigating with elegance

After reviewing the Modal method discussed on this particular page in the NextJS documentation, as well as exploring responses to questions on Stack Overflow like this one, I noticed that in all instances, when the page is refreshed, the modal simply displ ...

Encountered MissingSchemaError when implementing the mongoose-observer tool

My current project involves a standard setup of Node.js, express, mongoDB, and mongoose. I recently attempted to incorporate the mongoose-observer library to monitor changes in my mongodb database. For more information, please visit: https://www.npmjs.com ...

Unable to update React state on a component that is unmounted while utilizing Redux

Utilizing Redux for managing a global Dialog component, I am passing the child components to the Dialog component through Redux actions. You can find a functional example in this codesandbox: https://codesandbox.io/s/suspicious-keldysh-uuolb?file=/src/App ...

What is the best way to utilize a random user agent in Scrapy while integrating with Py

In my Scrapy project, I want to send a different user agent for each request. To achieve this, I included headers with a 'random user agent' in each request. The interesting thing is that Scrapy functions properly without pymongo. However, as soo ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: https://i.sst ...

CORS blocked in the live environment

error + whole page As a newcomer to JavaScript, I recently deployed my project. During development, everything was functioning well. However, I am now facing an issue with CORS when attempting to sign in (registration works without any problems, confirmin ...

Chapter 5 of Eloquent JavaScript's 3rd Edition presents Exercise 3

I'm struggling with an exercise in the latest edition of a book, specifically in Chapter 5 which covers Higher-Order Functions. The prompt for the exercise is as follows: "Similar to the some method, arrays also contain an every method. This method r ...

Unique mongoose schema with 2 different fields

My goal is to ensure that two fields are unique from each other and do not contain any duplicates. Here is the code snippet: const Connection = mongoose.model("Connection", new mongoose.Schema({ from_friend: { type: mongoose.Schema.Types.Obje ...