使用猫鼬生成自动增量字段?

Posted

技术标签:

【中文标题】使用猫鼬生成自动增量字段?【英文标题】:Generate auto increment field using Mongoose? 【发布时间】:2018-12-12 18:26:46 【问题描述】:

我有一个由四个字段 id、text、key、status 组成的数据库。我想添加另一个名为 order 的字段,它由一个数字组成,它是订单的表示形式。我也有删除文件的功能,所以删除后订单不会连续,我也希望订单连续且不重复。如果从数据库中删除某些文档,顺序会根据数据库中的文档数量自动调整。我有两个文件 index.js 和 items.js。我用过 mongoose、body-parser 和 expressjs。

我的订单字段不重复且连续。

index.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');

app.use(bodyParser.json());
app.use(cors());

Items = require('./items.js');

mongoose.connect('mongodb://localhost/taskDb');
var db = mongoose.connection;

app.get("/", (req, res) => 
    res.send('Visit /api/*****');
);

app.get("/api/items", (req, res) => 
    Items.getItems(function (err, items) 
        if (err) 
            throw err;
        
        res.json(items);
    );
);

app.post("/api/items", (req, res) => 
    var item = req.body;
    console.log(item + "item post");
    Items.addItem(item, function (err, items) 
        if (err) 
            throw err;
        
        res.json(items);
    );
);

app.delete("/api/items/:_key", (req, res) => 
    var key = req.params._key;
    Items.deleteItem(key, function (err, items) 
        if (err) 
            throw err;
        
        res.json(items);
    );
);

app.delete("/api/items/", (req, res) => 
    var status = "completed";
    Items.deleteItems(status, function (err, items) 
        if (err) 
            throw err;
        
        res.json(items);
    );
);

app.put("/api/items/:_key", (req, res) => 
    var key = req.params._key;
    var item = req.body;

    Items.updateItem(key, item, , function (err, items) 
        if (err) 
            throw err;
        
        res.json(items);
    );
);

app.put("/api", (req, res) => 
    Items.updateAllItem(function (err, items) 
        if (err) 
            throw err;
        
        res.json(items);
    );
);

app.listen(3005, () => 
    console.log('Listening on port 3005...');
);

items.js

var mongoose = require('mongoose');

var itemSchema = mongoose.Schema(
    text: 
        type: String,
        required: true
    ,
    key: 
        type: String,
        required: true
    ,
    status: 
        type: String,
        required: true
    ,
    order: 
        type: Number,
        required: true
    
);

var Item = module.exports = mongoose.model('item', itemSchema);

module.exports.getItems = function (callback, limit) 
    Item.find(callback).limit(limit);


module.exports.addItem = function (item, callback) 
    Item.create(item, callback);


module.exports.deleteItem = function (key, callback) 
    var query =  key: key ;
    Item.remove(query, callback);


module.exports.deleteItems = function (status, callback) 
    var query =  status: status ;
    Item.remove(query, callback);


module.exports.updateItem = function (key, item, options, callback) 
    var query =  key: key ;
    var update = 
        text: item.text,
        key: item.key,
        status: item.status
    
    Item.updateOne(query, update, , callback);


module.exports.updateItem = function (key, item, options, callback) 
    var query =  key: key ;
    var update = 
        text: item.text,
        key: item.key,
        status: item.status
    
    Item.updateOne(query, update, , callback);


module.exports.updateAllItem = function (callback) 
    console.log("Update All");
    Item.update(,  $set:  "status": "completed"  ,  "multi": true , callback);


module.exports.changeItemsOrder = function (items, callback) 
    var query = Item.remove(, callback);
    assert.ok(!(query instanceof Promise));

    // A query is not a fully-fledged promise, but it does have a `.then()`.
    query.then(function (doc) 
        // use doc
    );

    // `.exec()` gives you a fully-fledged promise
    var promise = query.exec();
    assert.ok(promise instanceof Promise);

    promise.then(function (doc) 
        // use doc
    );

【问题讨论】:

Create unique autoincrement field with mongoose的可能重复 答案解决了你的问题? 【参考方案1】:

您可以使用此库来增加您的订单字段:Mongoose Sequence

 var mongoose = require('mongoose');
  var AutoIncrement = require('mongoose-sequence')(mongoose);

  var ItemSchema = new mongoose.Schema(
    text: 
      type: String,
      required: true
    ,
    key: 
      type: String,
      required: true
    ,
    status: 
      type: String,
      required: true
    ,
    order: 
      type: Number
    
  );

  ItemSchema.plugin(AutoIncrement, id:'order_seq',inc_field: 'order');
  var ItemModel = mongoose.model('Item', ItemSchema);

  let newItem1= new ItemModel(
    text:'text1',
    key:'key1',
    status:'A'
  );
  newItem1.save();

  let newItem2= new ItemModel(
    text:'text2',
    key:'key2',
    status:'A'
  );
  newItem2.save();

  let newItem3= new ItemModel(
    text:'text3',
    key:'key3',
    status:'B'
  );
  newItem3.save();

现在,当您创建新项目时,order 字段将由库递增:

【讨论】:

以上是关于使用猫鼬生成自动增量字段?的主要内容,如果未能解决你的问题,请参考以下文章

文档创建猫鼬中的自动增量版本

文档创建猫鼬中的自动增量版本

如何在猫鼬中插入自动增量编号

自动生成的 prisma 增量字段

mySQL 数据库:重置自动增量字段

当猫鼬模型是新的时,有没有办法自动生成 ObjectId?