Node.js 限制mongoose模式长度

Node.js 限制mongoose模式长度,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,如何限制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,

如何限制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篇文章时,它应该自动删除/删除第一个项目并保存最新的文章。

在mongoose中定义模型后调用函数。您应该在mongoose l中查找虚拟函数,它们在文档中每次更改后都会被调用。

下面是我的字符串解决方案,您必须适应您的情况。 为了简单起见,我的向量限制为3,您的情况是50,只需更改代码

require("./connection");

var mongoose = require("mongoose");

const PostSchema = new mongoose.Schema({
  User: String,
  Posts: [String] //since I am not familar with the notation { type: Array }, I have decided to work with something I am familiar with
});

PostSchema.virtual("posts").set(function(newPost) {
  if (this.Posts.length >= 3) {//change here the size to 50
    this.Posts.pop();
    this.Posts.unshift(newPost);
  } else {
    this.Posts.unshift(newPost);
  }
});

Post = mongoose.model("Post", PostSchema);

Post.findOne({ User: "Jorge Pires" }).then(post => {
  post.posts = "this is nice!";
  post.save();
  console.log(post);
});

//--------------------------------------------------------------
//uncomment for creating your first dataset sample
// Post.create({
//   User: "Jorge Pires",
//   Posts: ["Hey there", "I am on stack overflow", "this is nice"]
// });
//-----------------------------------------------------------
它是如何工作的

新元素将从后面进入,如果向量大小超过其限制,最旧的元素将被删除,我的3和你的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();
          }
        });
      }
      
      函数newPost(post,limit){
      Post.find({},{},{sort:{Date:1}})。然后(resp=>{
      如果(分别长度<极限){
      新建帖子(Post.save();
      }否则{
      Post.findByIdAndRemove(resp[0].\u id.exec().catch(err=>{throw err});
      新建帖子(Post.save();
      }
      });
      }
      
      那么你想创建一个FIFO(先进先出)数据结构吗?嘿,你确定这是正确的`Posts:{type:Array}`?什么数组?@JorgePires一个帖子数组,帖子:[{id:xxxxxx…,postType:2,imgurl:'',标题:'lorem ipsum.},{id:xxxxxx…,postType:4,txt:'lorem ipsum…'.[最多50项]]我添加了一个解决方案,希望能有所帮助!你的解决方案似乎不会产生气泡效应,第一个和最后一个之间的运动会发生什么变化?现在我明白了!你想按日期排序,但我相信效果是一样的,不是吗?如果订单是FIFO。所以日期并不重要!对不起,我的错,你是对的,我看到你也更新了问题。我很高兴事情进展顺利!