gpt4 book ai didi

javascript - 更新数组中的最后一项

转载 作者:可可西里 更新时间:2023-11-01 09:38:15 25 4
gpt4 key购买 nike

我如何在该模式的实例上将数组中的最后一项作为目标:

let TrackerSchema = new Schema({
status: String,
start_date: { type: Date, default: Date.now },
end_date: { type: Date },
companyId: { type: mongoose.Schema.Types.ObjectId, ref: "Company" },
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
pauses: Array,
total_today: Number
});

跟踪器的实例如下所示:
{
"pauses": [{
"reason": "Lanch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
}, {
"reason": "Lanch",
"start": "2018-11-21T18:15:09.057Z"
}],
"_id": "...",
"status": "pause",
"start_date": "2018-11-21T18:12:43.896Z",
"companyId": "...",
"userId": "...",
"__v": 2
}

我需要暂停一下以获得最后一个项目,并向其添加一个“end”属性,我尝试过这种方法,但它并没有保存它,而且似乎正确的方法是使用诸如update或findOneAndUpdate之类的方法?
Tracker.findOne(query, (error, tracker) => {
checkForError(res, error);
let date = new Date();
let lastItem = tracker.pauses.length;
tracker.pauses[lastItem - 1].end = date;
tracker.status = "go";
tracker.save(error => {
checkForError(res, error);
res.send(tracker);
});
});

最佳答案

模式问题

不能为您更新的基本原因是, Mongoose 实际上要求被告知此类更改实际上有所作为。这本质上与它如何保留内部引用有关,然后决定了在您实际调用update()时作为save()语句发送回服务器的内容。

为此,“简单”的解决方法是在markModified()之前先在路径上调用 save() 方法:

tracker.markModified('pauses');
tracker.save((error) => {

然而,还有另一种方法,因为您曾经需要调用 markModified() 的唯一原因是因为 Mongoose 不了解您在基础元素上实际更改的内容。通常,人们在 Mixed类型上遇到此问题。但是,在您的情况下,您在 Array上定义了 pauses,而没有为该数组中的项目指定架构的结构。

因此,只需添加架构即可进行更改,而无需调用 markModified()
// pauses: Array // change this line
pauses: [{
reason: String,
start: Date,
end: Date
}]

一旦执行了这两个操作,对array元素的更改实际上将保留下来,但是正如您所注意到的, findOne()的整个过程然后进行这些更改并调用 save()并不是很理想。

因此,有一种方法可以自动完成此操作,但确实需要您进行一些更改。

原子更新

这里的核心问题是更新数组的最后一个元素。 MongoDB没有任何有效的方法可以以任何有效的方式查询或更新最后一个元素。这不是一个新问题,但共同的思路是解决此问题已有一段时间了。

反向对数组排序

基本原理是,当您向数组中添加项目时,您实际上可以通过给定属性对数组中的所有元素进行原子排序,以便始终有一定的数组顺序。这是一种反向排序的原因是,MongoDB实际上非常满意的是 的第一个数组元素。

因此,为了使数组元素保持有序,以便最新的始终是第一个元素,可以将 $sort 修饰符应用于 $push ,如下所示:
vat newPauses = [{ reason: "Next", start: new Date() }];

Tracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': newPauses, '$sort': { start: -1 } }
}
},
{ new: true }
)

这就是您每次想添加到数组中时代码的外观。由于新项目在 start中具有更新的日期值,因此 $sort 修饰符将重新排列数组,以便该最新项目实际上位于开头。

您甚至可以使用一个简单的语句来更新集合中的所有现有文档:
Tracker.updateMany(
{},
{
'$push': {
'pauses': { '$each': [], '$sort': { start: -1 } }
}
}
)

在这种情况下,给 $each 一个空数组,因此,当然在任何文档中都不会向该数组添加任何新项目。但是 $sort 被触发,然后所有项目将按其开始时间重新排序。

这种使用 $sort 的方法适合许多人,但是在某些情况下,它不是正确的解决方案。这就是为什么还有另一种方式的原因。

在数组之前

在这种情况下,您通常会认为自己没有真正的属性,例如 start,该属性应控制数组中元素的实际顺序,或者甚至在不希望有任何可能的情况下应用 $sort 或以任何方式移动现有元素的开销。

为了实现这一点,所需要做的就是将 $position 修饰符添加到 $push 语句中:
vat newPauses = [{ reason: "Next", start: new Date() }];

Tracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': newPauses, '$position': 0 }
}
},
{ new: true }
)

简而言之, $position 通过数组索引告诉MongoDB新元素应该在哪里。 0当然意味着数组的开始,这会将所有现有成员移到右侧,而不是在右侧添加新成员。

这里的唯一缺点是,如果不运行循环遍历所有文档并在集合中重写它们的过程,就无法真正以纯反向顺序真正更新现有数组成员,因为没有原子更新可以以相同方式反向整个数组 $sort 可以修改现有数组。因此,如果更改为使用 $position ,则设置成本会更高。

如果您需要这种方法,那么在 Update MongoDB field using value of another field上详细介绍了更新现有集合的方法。

示范

当然,这些最好通过演示来描述。这是展示所有方法的完整 list :
const { Schema, Types: { ObjectId } } = mongoose = require('mongoose');

const uri = 'mongodb://localhost:27017/trackdemo';
const opts = { useNewUrlParser: true };

// sensible defaults
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);

// schema defs

const pauseSchema = new Schema({
reason: String,
start: Date,
end: Date
})

const trackerSchema = new Schema({
pauses: Array
});

const altTrackerSchema = new Schema({
pauses: [pauseSchema]
});

const Tracker = mongoose.model('Tracker', trackerSchema);
const AltTracker = mongoose.model('AltTracker', altTrackerSchema);

// log helper

const log = data => console.log(JSON.stringify(data, undefined, 2));

// main

const getPauses = () => [
{
reason: "Lunch",
start: new Date("2018-11-21T18:13:22.835Z"),
end: new Date("2018-11-21T18:14:30.835Z")
},
{
reason: "Lunch",
start: new Date("2018-11-21T18:15:09.057Z")
}
];

(async function() {

try {

const conn = await mongoose.connect(uri, opts);

// Clean models
await Promise.all(
Object.entries(conn.models).map(([k,m]) => m.deleteMany())
);

// Test Tracker
await (async function() {
let pauses = getPauses();
let tracker = await Tracker.create({ pauses });
log(tracker);

let temp = tracker.pauses[tracker.pauses.length - 1];
temp.end = new Date();
log(temp);

tracker.pauses[tracker.pauses.length -1] = temp;
tracker.markModified('pauses');
await tracker.save();

let result = await Tracker.findById(tracker._id);
log(result);
})()

// Test AltTracker
await (async function() {
let pauses = getPauses();
let tracker = await AltTracker.create({ pauses });
log(tracker);

let temp = tracker.pauses[tracker.pauses.length - 1];
temp.end = new Date();
log(temp);

tracker.pauses[tracker.pauses.length -1] = temp;
//tracker.markModified('pauses');
await tracker.save();

let result = await AltTracker.findById(tracker._id);
log(result);
})()

// AltTracker atomic $sort method
await (async function() {

let _id = new ObjectId(); // keep ref for tests
let pauses = getPauses();

let tracker = await AltTracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': pauses, '$sort': { 'start': -1 } }
}
},
{ 'new': true, 'upsert': true }
);
log(tracker);

// update first

tracker = await AltTracker.findOneAndUpdate(
{ _id, 'pauses.0.end': { '$exists': false } },
{ '$set': { 'pauses.0.end': new Date() } },
{ 'new': true }
);
log(tracker);

})()

// AltTracker atomic $position method
await (async function() {

let _id = new ObjectId(); // keep ref for tests
let pauses = getPauses();

// Doing this twice purely for demo

let tracker = await AltTracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': [ pauses[0] ], '$position': 0 }
}
},
{ 'new': true, 'upsert': true }
);
log(tracker);

tracker = await AltTracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': [ pauses[1] ], '$position': 0 }
}
},
{ 'new': true, 'upsert': true }
);
log(tracker);

tracker = await AltTracker.findOneAndUpdate(
{ _id, 'pauses.0.end': { '$exists': false } },
{ '$set': { 'pauses.0.end': new Date() } },
{ 'new': true }
);
log(tracker);

})()

} catch(e) {
console.error(e)
} finally {
mongoose.disconnect()
}

})()

并显示所有更新发生的输出:
Mongoose: trackers.deleteMany({}, {})
Mongoose: alttrackers.deleteMany({}, {})
Mongoose: trackers.insertOne({ pauses: [ { reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:13:22 GMT"), end: new Date("Wed, 21 Nov 2018 18:14:30 GMT") }, { reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:15:09 GMT") } ], _id: ObjectId("5bf65cf6ae7b8639c3f5090d"), __v: 0 })
{
"pauses": [
{
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
},
{
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z"
}
],
"_id": "5bf65cf6ae7b8639c3f5090d",
"__v": 0
}
{
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z",
"end": "2018-11-22T07:38:30.883Z"
}
Mongoose: trackers.updateOne({ _id: ObjectId("5bf65cf6ae7b8639c3f5090d"), __v: 0 }, { '$set': { pauses: [ { reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:13:22 GMT"), end: new Date("Wed, 21 Nov 2018 18:14:30 GMT") }, { reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:15:09 GMT"), end: new Date("Thu, 22 Nov 2018 07:38:30 GMT") } ] }, '$inc': { __v: 1 } })
Mongoose: trackers.findOne({ _id: ObjectId("5bf65cf6ae7b8639c3f5090d") }, { projection: {} })
{
"pauses": [
{
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
},
{
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z",
"end": "2018-11-22T07:38:30.883Z"
}
],
"_id": "5bf65cf6ae7b8639c3f5090d",
"__v": 1
}
Mongoose: alttrackers.insertOne({ _id: ObjectId("5bf65cf6ae7b8639c3f5090e"), pauses: [ { _id: ObjectId("5bf65cf6ae7b8639c3f50910"), reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:13:22 GMT"), end: new Date("Wed, 21 Nov 2018 18:14:30 GMT") }, { _id: ObjectId("5bf65cf6ae7b8639c3f5090f"), reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:15:09 GMT") } ], __v: 0 })
{
"_id": "5bf65cf6ae7b8639c3f5090e",
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50910",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
},
{
"_id": "5bf65cf6ae7b8639c3f5090f",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z"
}
],
"__v": 0
}
{
"_id": "5bf65cf6ae7b8639c3f5090f",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z",
"end": "2018-11-22T07:38:30.915Z"
}
Mongoose: alttrackers.updateOne({ _id: ObjectId("5bf65cf6ae7b8639c3f5090e"), __v: 0 }, { '$set': { 'pauses.1.end': new Date("Thu, 22 Nov 2018 07:38:30 GMT") } })
Mongoose: alttrackers.findOne({ _id: ObjectId("5bf65cf6ae7b8639c3f5090e") }, { projection: {} })
{
"_id": "5bf65cf6ae7b8639c3f5090e",
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50910",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
},
{
"_id": "5bf65cf6ae7b8639c3f5090f",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z",
"end": "2018-11-22T07:38:30.915Z"
}
],
"__v": 0
}
Mongoose: alttrackers.findOneAndUpdate({ _id: ObjectId("5bf65cf6ae7b8639c3f50911") }, { '$setOnInsert': { __v: 0 }, '$push': { pauses: { '$each': [ { _id: ObjectId("5bf65cf6ae7b8639c3f50913"), reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:13:22 GMT"), end: new Date("Wed, 21 Nov 2018 18:14:30 GMT") }, { _id: ObjectId("5bf65cf6ae7b8639c3f50912"), reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:15:09 GMT") } ], '$sort': { start: -1 } } } }, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
"_id": "5bf65cf6ae7b8639c3f50911",
"__v": 0,
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50912",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z"
},
{
"_id": "5bf65cf6ae7b8639c3f50913",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
}
]
}
Mongoose: alttrackers.findOneAndUpdate({ _id: ObjectId("5bf65cf6ae7b8639c3f50911"), 'pauses.0.end': { '$exists': false } }, { '$set': { 'pauses.0.end': new Date("Thu, 22 Nov 2018 07:38:30 GMT") } }, { upsert: false, remove: false, projection: {}, returnOriginal: false })
{
"_id": "5bf65cf6ae7b8639c3f50911",
"__v": 0,
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50912",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z",
"end": "2018-11-22T07:38:30.940Z"
},
{
"_id": "5bf65cf6ae7b8639c3f50913",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
}
]
}
Mongoose: alttrackers.findOneAndUpdate({ _id: ObjectId("5bf65cf6ae7b8639c3f50914") }, { '$setOnInsert': { __v: 0 }, '$push': { pauses: { '$each': [ { _id: ObjectId("5bf65cf6ae7b8639c3f50915"), reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:13:22 GMT"), end: new Date("Wed, 21 Nov 2018 18:14:30 GMT") } ], '$position': 0 } } }, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
"_id": "5bf65cf6ae7b8639c3f50914",
"__v": 0,
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50915",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
}
]
}
Mongoose: alttrackers.findOneAndUpdate({ _id: ObjectId("5bf65cf6ae7b8639c3f50914") }, { '$setOnInsert': { __v: 0 }, '$push': { pauses: { '$each': [ { _id: ObjectId("5bf65cf6ae7b8639c3f50916"), reason: 'Lunch', start: new Date("Wed, 21 Nov 2018 18:15:09 GMT") } ], '$position': 0 } } }, { upsert: true, remove: false, projection: {}, returnOriginal: false })
{
"_id": "5bf65cf6ae7b8639c3f50914",
"__v": 0,
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50916",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z"
},
{
"_id": "5bf65cf6ae7b8639c3f50915",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
}
]
}
Mongoose: alttrackers.findOneAndUpdate({ _id: ObjectId("5bf65cf6ae7b8639c3f50914"), 'pauses.0.end': { '$exists': false } }, { '$set': { 'pauses.0.end': new Date("Thu, 22 Nov 2018 07:38:30 GMT") } }, { upsert: false, remove: false, projection: {}, returnOriginal: false })
{
"_id": "5bf65cf6ae7b8639c3f50914",
"__v": 0,
"pauses": [
{
"_id": "5bf65cf6ae7b8639c3f50916",
"reason": "Lunch",
"start": "2018-11-21T18:15:09.057Z",
"end": "2018-11-22T07:38:30.957Z"
},
{
"_id": "5bf65cf6ae7b8639c3f50915",
"reason": "Lunch",
"start": "2018-11-21T18:13:22.835Z",
"end": "2018-11-21T18:14:30.835Z"
}
]
}

关于javascript - 更新数组中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53418669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com