【发布时间】:2020-06-29 15:50:54
【问题描述】:
如何限制 mongoose 架构长度,在达到限制时从架构中删除第一个/最旧的项目并将新值附加到架构中?
const mongoose = require("mongoose");
const Post = new mongoose.Schema({
User: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
Posts: { type: Object }
Date: { type: Date, default: Date.now }
});
正如您在上面的代码中看到的那样,我有 Posts 架构,它接受没有限制的项目,但是假设我想将其限制为 50 个帖子,当用户添加超过 50 个帖子时,它应该自动删除/删除第一项并保存最新的帖子。
【问题讨论】:
-
那么你想创建一个FIFO(先进先出)数据结构吗?
-
嘿,你确定这是正确的`帖子:{类型:数组}`?什么数组?
-
@JorgePires 一个帖子数组,帖子:[ { _id: xxxxxx..., postType: 2, imgurl: 'url-to-image', caption: 'lorem ipsum.'}, { _id: xxxxxx..., postType: 4, txt: 'lorem ipsum...'}, .... [最多 50 项] ]
-
A 我添加了一个解决方案,希望对您有所帮助!