【问题标题】:Limit mongoose schema length限制猫鼬模式长度
【发布时间】: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 我添加了一个解决方案,希望对您有所帮助!

标签: node.js mongodb mongoose


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    因为我找不到任何 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();
        }
      });
    }
    

    【讨论】:

    • 您的解决方案似乎没有产生气泡效果,第一个和最后一个之间的移动会发生什么?
    • 现在我明白了!你想按日期排序,但我相信效果是一样的,不是吗?如果订单是先进先出。所以日期无关紧要!
    • 对不起,我的错,你是对的,我看到你也更新了问题。我很高兴事后一切顺利!
    【解决方案3】:

    这是我的字符串解决方案,你必须适应你的情况。 为简单起见,我的向量限制为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 将删除最旧的元素。 它会产生“气泡效应”,当您引入新元素时,最旧的元素会自动移至头部并最终被淘汰。

    参考文献

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 2016-08-05
      • 2015-03-08
      • 2015-05-03
      • 2020-09-18
      • 2012-02-02
      • 2020-08-01
      • 2021-09-21
      相关资源
      最近更新 更多