简体   繁体   中英

Mongoose field how to auto increment

I have a mongoose Schema like below:

 var userSchema = new Shema({
   userName: {type: String, default: "ABC"},
   lastLoginTime: {type: Date, default: Date.now},
   loginTimes: {type: Number, default: 1},
   ......
 });

And I want to update lastLoginTime and let loginTimes plus one when user login every time.
It's easy to update lastLoginTime , just give it a new time string.
But how can I make loginTimes plus one every time.

Well you can always use the $inc operator with a form of "update"

Model.update(
    { _id: docId },
    {
       "$set": { "lastLoginTime": new Date() },
       "$inc": { "loginTimes": 1 }
    },
    function(err,numaffected) {

    }
)

That is a general MongoDB preferred way of doing things as there is minimal traffic sent for each actual update.

Also see the .findByIdAndUpdate() method for mongoose since this is likely restricted to one document.

An alternate is to use "pre save" hooks to be very mongoose about it, but it seems sort of cumbersome to me to retrieve and modify a document when you don't really need things like validation for this sort of update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM