如何在该模式的实例上定位数组中的最后一项:
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);
});
});
答案 0 :(得分:2)
这不是为您更新的基本原因是,猫鼬实际上要求被告知此类更改实际上有所作为。这本质上与它如何保留内部引用有关,然后决定了在您实际调用update()
时作为save()
语句发送回服务器的内容。
“简单”解决方案是在您save()
之前在路径上调用markModified()
方法:
tracker.markModified('pauses');
tracker.save((error) => {
还有另一种方法,因为您需要调用markModified()
的唯一原因是因为猫鼬不了解您在基础元素上实际更改的内容。通常,人们在Mixed
类型上遇到此问题。但是在您的情况下,您在Array
上定义了pauses
,而没有为该数组中的项目指定架构的结构。
因此,只需添加架构即可进行更改,而无需调用markModified()
// pauses: Array // change this line
pauses: [{
reason: String,
start: Date,
end: Date
}]
一旦执行了这两个操作,对array元素的更改实际上都会保留下来,但是正如您注意到findOne()
的整个过程,然后进行这些更改并调用save()
并不是很理想。
因此,有一种自动进行此操作的方法,但这确实需要您进行一些更改。
这里的核心问题是更新数组的 last 元素。 MongoDB没有任何有效的方法可以以任何有效的方式查询或更新 last 元素。这不是一个新问题,但共同的思路是解决此问题已有一段时间了。
对数组进行反向排序
基本原理是,当您向数组中添加项目时,您实际上可以按照给定的属性 atomically 对数组中的所有元素进行排序,以便始终有一定的数组顺序。这是反向排序的原因是,MongoDB实际上非常满意的是 first 数组元素。
因此,为了保持数组元素有序,以便 latest 始终是 first 元素,您可以将$sort
修饰符应用于{{3} },如下所示:
vat newPauses = [{ reason: "Next", start: new Date() }];
Tracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': newPauses, '$sort': { start: -1 } }
}
},
{ new: true }
)
这就是您每次想添加到数组中时代码的外观。由于新项目在start
中具有更新的日期值,因此$push
修饰符将重新排列其数组,以便该最新项目实际上位于开始位置。
您甚至可以使用一个简单的语句更新收藏集中的所有现有文档:
Tracker.updateMany(
{},
{
'$push': {
'pauses': { '$each': [], '$sort': { start: -1 } }
}
}
)
在这种情况下,$sort
被赋予一个空数组,因此,当然在任何文档中都不会向该数组添加新项目。但是$each
被触发,然后所有项目将按其开始时间重新排序。
这种使用$sort
的方法适合许多人,但是在某些情况下,它不是正确的解决方案。这就是为什么有另一种方式的原因。
添加到数组
这里的一般情况是,您要么没有真正拥有start
之类的属性来控制数组中元素的实际顺序,要么甚至没有不想花费任何可能的开销来应用$sort
或以任何方式移动现有元素。
要实现这一目标,只需在您的$sort
语句中添加$position
修饰符:
vat newPauses = [{ reason: "Next", start: new Date() }];
Tracker.findOneAndUpdate(
{ _id },
{
'$push': {
'pauses': { '$each': newPauses, '$position': 0 }
}
},
{ new: true }
)
简而言之,$push
通过数组索引告诉MongoDB新元素应该在哪里。 0
当然意味着数组的开始,这会将所有现有成员移到右侧,而不是在右侧添加新成员。
这里唯一的缺点是,如果不运行循环遍历所有文档并在集合中重写它们的过程,就无法真正以纯反向顺序真正更新现有数组成员,因为没有原子更新可以颠倒整个数组。 $position
可以修改现有数组的方式相同。因此,如果更改为使用$sort
,则设置成本会更高。
如果您要使用这种方法,则在$position
当然,这些最好通过演示来描述。这是展示所有方法的完整清单:
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"
}
]
}