限制猫鼬模式长度

时间:2020-03-18 14:19:44

标签: node.js mongodb 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 }
});

正如您在代码中上面看到的那样,我具有“帖子”架构,它可以无限制地接受项目,但是,如果用户添加的帖子超过50个,我想将其限制为50个帖子,则应该自动删除/删除第一项,然后保存最新的帖子。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

因为我找不到任何解决该问题的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();
    }
  });
}

答案 2 :(得分:0)

这是我针对String的解决方案,您必须适应您的情况。 为了简单起见,我的向量限制为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),则最旧的元素将被删除。 当您引入新元素时,它会创建“气泡效果”,最旧的元素将自动移到头部并最终被消除。

引用

相关问题