Meteor.js - 在方法上创建自动增量字段

时间:2015-09-15 08:45:08

标签: javascript meteor

这里的方法“saveProject”写入数据集合“Projects”。

Meteor.methods({
  'saveProject': function (project) {
    check(project.name, String);
    currentId = Projects.findOne({},{sort:{id:-1}}).id || 1;
    project.id = currentId + 1;
    project.userId = Meteor.userId();
    project.dateentered = new Date();
    project.lastupdate = new Date();
    if (!project.datedue) {
      project.datedue = new Date();
    }
    project.invited = [];
    return Projects.insert(project);
  }
});

此代码创建一个给定的名为“id”并指定已保存“项目”的自动编号。

currentId = Projects.findOne({},{sort:{id:-1}}).id || 1;
project.id = currentId + 1;

问题是此代码仅在首次保存集合“项目”时才起作用。如何在将第一个草稿写入数据集“项目”

的同时修改此代码以延长工作时间

2 个答案:

答案 0 :(得分:3)

我建议为自动递增序列字段创建单独的集合。

例如:

if (Meteor.isServer) {
    Meteor.startup(function () {
        Counters._ensureIndex({"type": 1});
        if (Counters.find({type: "projectId"}).count() == 0) Counters.insert({type: "projectId", seq: 0});
        Projects.insert({seq: getNextSequence("projectId"), name: "Project 1"});
        Projects.insert({seq: getNextSequence("projectId"), name: "Project 2"});
        Projects.insert({seq: getNextSequence("projectId"), name: "Project 3"});
        Projects.insert({seq: getNextSequence("projectId"), name: "Project 4"});
    });
}

Projects = new Mongo.Collection("projects");
Counters = new Mongo.Collection("counters");

getNextSequence = function (name) {
    Counters.update({type: name}, {$inc: {seq: 1}});
    var ret = Counters.findOne({type: name});
    return ret.seq;
};

输出:

{ "_id" : "vMmxNRCxroicxYftf", "seq" : 1, "name" : "Project 1" }
{ "_id" : "g8EMSooQK7JQ8bTNL", "seq" : 2, "name" : "Project 2" }
{ "_id" : "RZw3JxnMohinJ5x3g", "seq" : 3, "name" : "Project 3" }
{ "_id" : "BEoyoo3jJPRCgjTuc", "seq" : 4, "name" : "Project 4" }

答案 1 :(得分:1)

解决方案:

rm app/cache/* -rf