【问题标题】:How to update a array of numbers in mongoose如何更新猫鼬中的数字数组
【发布时间】:2022-01-18 05:28:25
【问题描述】:

我无法更新 MongoDB (Mongoose) 中文档内的数组。这是我对库存模型的定义。

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

这是 MongoDB 中的一个文档

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

我在 mongoose 中运行它,但 PastPrices 没有更新。我希望能够每隔几秒将其推送到这个数组中,然后将其渲染到图表中

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

我没有收到任何错误,但它只是没有更新

【问题讨论】:

    标签: javascript typescript mongodb mongoose mongodb-query


    【解决方案1】:

    updateOne 返回一个Query,它不会立即执行您的更新。从Mongoose guide for Queries 中可以看出:

    可以通过以下两种方式之一执行猫鼬查询。首先,如果你传入一个回调函数,Mongoose 会异步执行查询并将结果传递给回调。

    查询也有 .then() 函数,因此可以用作承诺。

    意味着你可以像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);
    });
    

    如果你想使用 Promises,你也可以使用 thenexec。来自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
    });
    

    如果在异步方法中,也可以await查询:

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

    【讨论】:

    • 我对回调方法的参数来自哪里有点困惑。 You use function (err, person) 没有定义它是什么类型。此外,如果我只想更新数据库,我会在回调函数中放入什么?
    • updateOne 的回调有两个参数,(error, writeOpResult),其中writeOpResultresult 记录的here 对象。 @SarthakSin
    【解决方案2】:

    您的查询是正确的,但是为了让查询返回更新的数据,您需要传递额外的配置{ new: true }。如果不传递,查询会更新数据,但会返回旧数据。

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

    【讨论】:

    • 我刚刚将该部分添加到查询的末尾,并且数据库没有更新。我应该有额外的代码然后将其发送到数据库吗?
    • 您是否检查了数据库中是否有值为“TSLA”的文档?
    • { "_id": { "$oid": "61e5d0e1dfda4d7c85dc8fe2" }, "PastPrices": [ 2 ], "ticker": "TSLA", "Price": 2, "Amount": 0, "__v": 0 } 在我的 mongoDB 数据库中
    • 也许您有多个带有"ticker": "TSLA" 的文档。你能检查一下吗? updateOne 将找到它匹配的第一个文档并更新该文档。
    • 我查了一下,只有一个 TSLA。我刚刚更新它,问题是我没有在查询结束时执行 .exec
    猜你喜欢
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2021-12-28
    • 2016-11-09
    • 2023-03-04
    • 2019-09-14
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多