如何限制猫鼬模式的长度,当达到限制时从模式中删除第一个/最旧的项,并将新值附加到模式中?
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 }
});
如您在代码中的上面所看到的,我具有“帖子”架构,它可以无限制地接受项目,但是,当用户添加50个以上的帖子时,我想将其限制为50个帖子,它应该自动删除/删除第一个项目,并且保存最新帖子。
因为我找不到解决它的任何MongoDB方法。这是我为实现这一目标所做的事情:
function newPost(post, limit) {
Post.find({}, {}, { sort: { Date: 1 } }).then(resp => {
if (resp.length < limit) {
new Post(post).save();
} else {
Post.findByIdAndRemove(resp[0]._id).exec().catch(err => { throw err });
new Post(post).save();
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句