Domanda

If I have a Schema with the key expires; how could I get the value of that key to update automatically each time the document is updated? This might be more complicated, but, I am upserting so this value would need to be set on the initial insert and then updated on each upsert.

So, when the document is inserted:

{
  expires: *an hour from the insert*
}

and when it's updated (via upsert):

{
  expires: *an hour from the update*
}

I'm using Mongoose if that has this functionality built in. If Mongodb does not support it nor does Mongoose I'll just have to work out the expires: and update the value but it would be nice to have this done automagically in Mongodb!

In fact, it would not den really need to work on the insert; as I could check if the expires was empty and extract the time from the _id.

As always, any help is greatly appreciated!

È stato utile?

Soluzione

Mongoose middleware doesn't fire on update calls, so you'd need to do it yourself:

var expires = new Date();
expires.setHours(expires.getHours() + 1);
MyModel.update({...}, {$set: {expires: expires, ...}}, {upsert: true}, callback);

Also, I don't know your use case, but you should also look at Mongo's built-in support for expiring data from collections if that's what you're trying to do. See here.

Altri suggerimenti

Recent versions of Mongoose allow passing { timestamps: true } as an option when creating new models. This feature will automatically set createdAt and updatedAt. Here is the documentation.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top