[英]Mongoose: Remove elements from array of objects in Mongo if condition is met
I have an array of objects that stores the date of an API request along with the JSON values of the request and response.我有一个对象数组,用于存储 API 请求的日期以及请求和响应的 JSON 值。 The issue is I don't want this log to get massive.问题是我不希望这个日志变得庞大。 I need to set a max limit or remove entries older than a particular date.我需要设置最大限制或删除早于特定日期的条目。
I'm trying to use a mongo / mongoose query to delete elements of an array when the date value of that object is greater than 5 days.当该对象的日期值大于 5 天时,我正在尝试使用 mongo / mongoose 查询来删除数组的元素。
This is the relevant section the mongo model:这是mongo模型的相关部分:
log: [
{
select: false,
date: {
type: Date,
default: Date.now,
select: false
},
request: { type: String, select: false },
response: { type: String, select: false }
}
]
I've tried using updateMany and $pull我试过使用 updateMany 和 $pull
const fiveDaysAgo = moment()
.subtract(5, 'day')
.format('YYYY-MM-DD');
// Ensure log value exists in collection
// Remove any log entry older than five days
Collection.updateMany(
{ log: { $exists: true } },
{ $pull: { 'log.$[].date': { $gte: fiveDaysAgo } } }
).then(data => console.log(data));
This produces this error:这会产生此错误:
(node:1957) UnhandledPromiseRejectionWarning: MongoError: Cannot apply $pull to a non-array value
If there was a way to set a max value of entires in the array of objects, and automatically pop the oldest entry off when the new entry is inserted that would also work for me.如果有一种方法可以在对象数组中设置整数的最大值,并在插入新条目时自动弹出最旧的条目,这也适用于我。
Based on your schema log
is just an array of documents which contain a field date
so if you want to build a condition for that field your update can look like below:基于您的架构log
只是包含字段date
的文档数组,因此如果您想为该字段构建条件,您的更新可能如下所示:
Collection.updateMany(
{ log: { $exists: true } },
{ $pull: { 'log': { date: { $lte: fiveDaysAgo } } } }
).then(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.