简体   繁体   English

使用Mongoose生成自动增量字段?

[英]Generate auto increment field using Mongoose?

I have a database which consist of four fields id, text, key, status. 我有一个数据库,包括四个字段id,text,key,status。 I want to add another field named order which consist of a number, which is representation of the order. 我想添加另一个名为order的字段,该字段由一个数字组成,这是一个代表的表示。 I also have functionality to delete documents so after deletion order will not be continuous, i also want to have order continuous and non repeating. 我也有删除文件的功能,所以删除顺序不连续后,我也希望订单连续不重复。 If some documents are deleted from db order is adjusted automatically based on the number of documents in database.I have two files index.js and items.js. 如果从数据库中删除某些文档,则会根据数据库中的文档数自动调整。我有两个文件index.js和items.js。 I have used mongoose, body-parser and expressjs. 我使用过mongoose,body-parser和expressjs。

My order field is non repeating and continous. 我的订单字段不重复且连续。

index.js 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 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
    });
}

You can use this library for increment your order field: Mongoose Sequence 您可以使用此库来增加订单字段: 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();

Now when you create a new Item the order field will be incremented by the library: 现在,当您创建新项目时, 订单字段将由库递增:

自动增量字段

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

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