Reputation: 628
How can I limit mongoose schema length, remove the first/oldest item from the schema when it reaches the limit and appends the new value to the schema?
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 }
});
As you can see above in the code, I have Posts schema, it accepts items with no limit, but let's say I want to limit it with 50 posts when a user adds more than 50 posts it should automatically delete/remove the first item and save the newest post.
Upvotes: 1
Views: 774
Reputation: 628
since I couldn't find any MongoDB way of solving it. here's what I did to achieve this:
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();
}
});
}
Upvotes: 1
Reputation: 632
Here goes my solution for String, you must adapt for your case. For the sake of simplicity, my vector is limited to 3, your case 50, just change the code!
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"]
// });
//-----------------------------------------------------------
How it works?
The new elements will enter in the back, and the oldest will be removed if the vector size exceed its limit, mine 3 and yours 50. It creates the "bubble effect", as you introduce new elements, the oldest ones automatically will move to the head and be eliminated eventually.
references
Upvotes: 0
Reputation: 162
Call a function after defining your model in mongoose. You should look up virtual functions in mongoose l, they get invoked after every change in you document.
Upvotes: 1