如何增加mongodb中的id

时间:2017-01-23 13:08:29

标签: mongodb mongoose

import mongoose from 'mongoose';
// mongoose Schema is what is used to define attributes for our documents
var Schema = mongoose.Schema;
//connect to a MongoDB database
var db = mongoose.connect('mongodb://127.0.0.1:27017/student');
//Connection establishment between mongoose and mongodb
mongoose.connect('connected', function() {
    console.log("database connected successfully")
});


var userSchema = new Schema({

    id:{
        type:Number,
            unique:true,
            autoIndexId:true
    },
    Name: {
        type: String,
        required: true,
                unique:false
    },
    Age: {
        type: Number,
        required: true
    }
},   {
    collection: ('studentcollection')
});

var User = mongoose.model('User', userSchema);

function createStudent(name, age, cb) {
    var list = new User({
            id:4,
        Name: name,
        Age: age
    });

    list.save(function(err) {
        if (err) return cb(err);
        return cb();
    });
}

function listStudent(cb) {
    User.find({}, function(err, studentcollection) {
        if (err) return cb(err);
        return cb(null, studentcollection);
    }).select('-__v');
}


exports.createStudent = createStudent;
exports.listStudent = listStudent;

User.findByIdAndRemove(2,function(err){
    if(err) throw err;
    console.log("deleted");
});

这是我的代码,我需要增加id,当我从服务器接收数据时它应该是唯一的,当我删除id时,id值也必须更新。我遇到了自动增量,但是当我删除一个特定的ID时,它不会更新id。是他们的任何其他方法,所以我可以增加id。

1 个答案:

答案 0 :(得分:0)

使用mongoose-auto-increment模块,

var mongoose = require('../lib/mongoose');
    Schema = mongoose.Schema;
    autoIncrement = require('mongoose-auto-increment');
    companySchema = require('./company').Company;

autoIncrement.initialize(mongoose);

var schema = new Schema({
    itemId: {
        type: Number,
    },
    itemName: {
        type: String,
        required: true,
        unique: true
    },
    providerCompany: [{
        type: String,
    }]

});

var productSchema = mongoose.model('Product', schema);

schema.plugin(autoIncrement.plugin, {model: 'Product', field: 'itemId'});
module.exports.Product = productSchema;

https://github.com/miroslav-grabinskiy/Api/blob/master/Avalon/models/product.js