Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Mongoose support the concept of a fixed queue array

I am looking to implement a time based queue with a fixed length where the old items pop off the back.

For instance I have a list of comments constrained to 10 items, the 11th item comes in and the oldest on falls off the back.

If not supported in Mongoose, can someone tell me some trickery I can use? (pre / etc)

Many Thanks

like image 442
Slappy Avatar asked Jul 10 '13 07:07

Slappy


People also ask

What is Mongoose used for?

Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A "collection" of "documents" in a MongoDB database is analogous to a "table" of "rows" in a relational database.

How does Mongoose schema work?

With Mongoose, you would define a Schema object in your application code that maps to a collection in your MongoDB database. The Schema object defines the structure of the documents in your collection. Then, you need to create a Model object out of the schema. The model is used to interact with the collection.

Is Mongoose A ORM?

Mongoose is similar to an ORM (Object-Relational Mapper) you would use with a relational database. Both ODMs and ORMs can make your life easier with built-in structure and methods. The structure of an ODM or ORM will contain business logic that helps you organize data.

What is $Set in Mongoose?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.


2 Answers

MongoDB has introduced capped arrays (from v2.4) which could be used to limit the number of elements in an array.

You can see some examples at limit number of elements

like image 186
Satheesh Kumar Avatar answered Sep 18 '22 12:09

Satheesh Kumar


db.myCollection.update({"arrayField.10": {$exists: true}}, {$pop: {"arrayField": 1}})

The "a.10" key checks if element 10 exists in "arrayField", which would mean the array size is equal to or greater than 10. If it does, pop 1 element off the back of the array atomically.

May not be the best solution for your case, but hopefully this may set you off in the right direction.

like image 20
Brandon Silva Avatar answered Sep 21 '22 12:09

Brandon Silva