简体   繁体   中英

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

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 }
);

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}}
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM