我無法更新 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
}
我在貓鼬中運行它并且 PastPrices 沒有更新。我希望能夠每隔幾秒鐘將其推送到該陣列中,然后將其渲染為圖表
stock.updateOne({ticker: "TSLA"},
{ $push: { PastPrices:1}}
);
我沒有收到任何錯誤,但它只是沒有更新
uj5u.com熱心網友回復:
updateOne回傳一個Query,它不會立即執行您的更新。來自Mongoose guide for Queries它指出:
mongoose 查詢可以通過以下兩種方式之一執行。首先,如果你傳入一個回呼函式,Mongoose 將異步執行查詢并將結果傳遞給回呼。
查詢還具有 .then() 函式,因此可以用作承諾。
這意味著您可以像執行查詢的檔案中那樣傳遞回呼函式:
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); });
你也可以使用then或者exec如果你想使用 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}}
);
uj5u.com熱心網友回復:
您的查詢是正確的,但為了讓查詢回傳更新的資料,您需要傳遞額外的 config { new: true }。如果不傳遞,查詢會更新資料,但會回傳舊資料。
stock.updateOne(
{ ticker: "TSLA" },
{ $push: { PastPrices:1 } },
{ new: true }
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414129.html
標籤:
