How to dynamically update field in collection based on condition?

Hi,

I need to build a db handling book rentals, if a book is not returned on time (3 days) a monetary penalty needs to be applied to the document and the book should be marked as “delayed” so it’s easy to query and find what books have not been returned on time.

I have this mongoose schema:
const rentSchema = new schema(

{

    movieID: { type: Number, required: true },

    customerID: { type: Number, required: true },

    amount: { type: Number, required: true },

    totalCost: { type: Number, required: true },

    returnDate: { type: Date, default: Date.now() + 3 * 24 * 60 * 60 * 1000 },

    delayed: { type: Boolean, default: false },

    penalty: { type: Number },

},

{ timestamps: true }

);

But I’m unsure how I can automize this process?

Is there a way to insert data conditionally based on the returnDate somehow?

I found a similiar thread on Stackoverflow discussing this theme and the author was recommended to use virtual properties with a condition in my case it could be currentDate >= returnDate, but when I checked the documentation it says that virtual properties can’t be used for queries or to insert data into the db? So how could this be useful in this case then?
If not virtual properties, is there some other way I could deal with this?

Hello @Olle_Bergkvist, welcome to the MongoDB Community forum!

But I’m unsure how I can automize this process?
Is there a way to insert data conditionally based on the returnDate somehow?

Since, everyday you are looking for delayed returns - run an update operation to update the collection and set a field delayedDays: n (where n is the number of days late). So, when the renter returns the book, you will know immediately how many days the book is returned late. There is no way to automate this process, but to run a job everyday for all the renters, perhaps at the start of the day before any of the renters are queried.


I found a similiar thread on Stackoverflow discussing this theme …

It is not clear what you are trying to say, but do include the link to the post so that others reading this post can see what you are trying to say and respond.

The Mongoose Virtuals topic on Limitations says:

Mongoose virtuals are not stored in MongoDB, which means you can’t query based on Mongoose virtuals.

So, you will not be able to use this feature for this use case.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.