简体   繁体   English

Node和Mongoose创建/使用字段为每个新添加的字段增加+1

[英]Node and Mongoose create/use field that increases +1 for each new added

I'm going to try and keep this as simple as possible. 我将尝试使其尽可能简单。 I've spent all day testing modules to do this, and at this point have gotten so confused with everything I figured this would be my best option. 我花了一整天的测试模块来做到这一点,而此时,我与一切都感到困惑,我认为这将是我最好的选择。

I have a Schema: 我有一个架构:

var AppSchema = new mongoose.Schema({
    appid: { type: Number },
    appname: { type: String },
    appdesc: { type: String }
});
app.db.model('userApp', AppSchema);

Using Express and processing a POST, I then want to create "a new app" 然后使用Express并处理POST,然后创建“新应用”

app.post('/app/new', function (req, res) {
    var newApp = app.db.models.userApp({
        appid: functionToIncreaseByOne(),
        appname: req.param('appname'),
        appdesc: req.param('appdesc')
    });
    newApp.save();
});

I removed most of the bloat in there, redirects, etc, just to keep this simple. 为了简化起见,我删除了其中的大多数膨胀,重定向等。 So what I would like to do is to have the APPID be set at 1 first the first app added, and then increase +1 for each new app that is added. 因此,我想做的就是首先将添加的第一个应用的APPID设置为1,然后为每个添加的新应用增加+1。 It seems so simple but i've gone through so many complex examples my head just hurts now. 看起来很简单,但是我经历了很多复杂的例子,现在我的头很痛。

I thought about just using .find and then orderby to find the app with the highest appid, then just use that and add +1 to it, but i'm sure there has to be another, easier way. 我考虑过只使用.find然后使用orderby查找具有最高appid的应用程序,然后使用它并为其添加+1,但是我敢肯定必须有另一种更简单的方法。 I DON'T want the appid to change when there is an update, the only time I want it to be set is on that first POST route to create the new app. 我不希望有更新时更改appid,我唯一要设置的时间是在第一条POST路由上创建新应用。

If someone could please help me out here or at least point me in the right direction, I would greatly appreciate it. 如果有人可以在这里帮助我,或者至少指出正确的方向,我将不胜感激。

I can see several ways to do so. 我可以看到几种方法。

First , you may store last_id in a global variable: 首先 ,您可以将last_id存储在全局变量中:

var last_id = 0;

app.post('/app/new', function (req, res) {
  var newApp = app.db.models.userApp({
    appid: ++last_id,
    appname: req.param('appname'),
    appdesc: req.param('appdesc')
  });
  newApp.save();
});

You may add a proper initialization of last_id , so it'll "catch up" with your database when your application starts. 您可以添加一个正确的last_id初始化,以便在您的应用程序启动时将“跟上”数据库。

The only disadvantage of this approach is that you can't use it if you have several node.js processes. 这种方法的唯一缺点是,如果您有多个node.js进程,则无法使用它。

Second , you may query your database each time you want to create new document: 其次 ,您每次想创建新文档时都可以查询数据库:

app.post('/app/new', function (req, res, next) {
  app.db.models.userApp.find()
    .sort({_id: -1})
    .limit(1)
    .select('_id')
    .exec(function (err, docs) {
      if (err) return next(err);
      var newApp = app.db.models.userApp({
        appid: docs[0]._id,
        appname: req.param('appname'),
        appdesc: req.param('appdesc')
      });
      newApp.save();
    })
});

But there is no way to guarantee that the next find operation will occur after the previous save operation. 但是无法保证下一个find操作将在上一个save操作之后发生。 So, there is a chance that your app will try two save two different docs with one _id . 因此,您的应用可能会尝试使用两个_id保存两个不同的文档。 It's why you should avoid this solution if possible. 这就是为什么您应该避免这种解决方案的原因。

Third , you may use some other storage (eg Redis) to atomically increment last_id every time you're reading it: 第三 ,每次阅读时,您都可以使用其他存储(例如Redis)以原子方式递增last_id

var RedisClient = require('redis').createClient()

app.post('/app/new', function (req, res, next) {
  RedisClient.incr('last_id', function (err, next_id) {
    if (err) return next(err);
    var newApp = app.db.models.userApp({
      appid: next_id,
      appname: req.param('appname'),
      appdesc: req.param('appdesc')
    });
    newApp.save();
  })
});

This solution is the best one, but it require additional database to be installed. 此解决方案是最佳解决方案,但需要安装其他数据库。

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

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