简体   繁体   English

猫鼬字段如何自动递增

[英]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. 而且我想更新lastLoginTime并在用户每次登录时让loginTimes加1。
It's easy to update lastLoginTime , just give it a new time string. 更新lastLoginTime很容易,只需给它一个新的时间字符串即可。
But how can I make loginTimes plus one every time. 但是我怎样才能使loginTimes每次加一。

Well you can always use the $inc operator with a form of "update" 好吧,您始终可以将$inc运算符与“ 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. 这是MongoDB首选的一般处理方式,因为每次实际更新发送的流量都最少。

Also see the .findByIdAndUpdate() method for mongoose since this is likely restricted to one document. 另请参阅.findByIdAndUpdate()方法以了解猫鼬,因为这可能仅限于一个文档。

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. 一种替代方法是使用“ pre save”钩子使其非常猫鼬,但是当您确实不需要诸如验证这类更新之类的东西时,检索和修改文档对我来说似乎有点麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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