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

时间:2018-07-04 10:30:26

标签: javascript node.js express mongoose mongoose-schema

我有一个数据库,由四个字段ID,文本,键,状态组成。我想添加另一个名为order的字段,该字段由数字组成,该数字表示该订单。我还具有删除文档的功能,因此删除顺序将不再连续,我也希望顺序连续且不重复。如果从数据库中删除了一些文档,则会根据数据库中的文档数量自动调整顺序。我有两个文件index.js和items.js。我用过猫鼬,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
    });
}

1 个答案:

答案 0 :(得分: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();

现在,当您创建新商品时,订单字段将由库增加:

Auto Increment Field