Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
How to update a array of numbers in mongoose

I am unable to update an array inside of a document in MongoDB (Mongoose). Here is my definition for a stock model.

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

Here is one document in MongoDB

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

I am running this in mongoose and the PastPrices is not updating. I want to be able to push every few seconds into this array and then render it into a chart

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

I am not getting any error thrown but it is just not updating

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

updateOne returns a Query, which doesn't execute your update immediately. From the Mongoose guide for Queries it states:

A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback.

A query also has a .then() function, and thus can be used as a promise.

Meaning you can pass a callback function as in the documentation for executing Queries:

const Person = mongoose.model('Person', yourSchema);
// find each person with a last name matching 'Ghost', selecting the `name` and > `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
 if (err) return handleError(err);
 // Prints "Space Ghost is a talk show host".
  console.log('%s %s is a %s.', person.name.first, person.name.last,
    person.occupation);
});

You can also use then or exec if you want to use Promises. From the Mongoose documentation for promises:

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) {
 // use doc
});

// `.exec()` gives you a fully-fledged promise
const promise = Band.findOne({name: "Guns N' Roses"}).exec();
assert.ok(promise instanceof Promise);

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

If in an async method, you can also await the query:

await stock.updateOne({ticker: "TSLA"},
        { $push: { PastPrices:1}}
    );
over 4 years ago · Santiago Trujillo Report

0

Your query is correct, but in order for the query to return updated data, you need to pass additional config { new: true }. If you don't pass it, the query will update the data, but it will return old data.

stock.updateOne(
  { ticker: "TSLA" },
  { $push: { PastPrices:1 } },
  { new: true }
);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!