MongoDB自动增量不起作用

时间:2018-02-17 11:12:34

标签: mongodb express

我尝试使用数字_id创建用户集合,但它创建为

{
    "_id": {
        "$oid": "5a880c0ca48be2060035cb97"
    },
    "email": «example@gmail.com",
    "name": «IV",
    "password":       "$2a$10$bozaPRj2K7rcS8ZkmO9TkOUFKgCqKFD3C3nB7iB04JtYIkS8z1Kxe",
    "__v": 0
}

我使用mongoose和ExpressJs,这3个文件包含用数字ID注册的代码。我找不到解决方案,为什么它不起作用。

在counter.js创建计数器:

var mongoose = require('mongoose');

var CounterSchema = new mongoose.Schema({
    _id: { type: String, required: true },
    seq: { type: Number, default: 0 }
});

var userCounter = mongoose.model('userCounter', CounterSchema);

module.exports = userCounter;

在user.js

创建用户
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var userCounter = require('../models/counter');

var UserSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    password: {
        type: String,
        required: true,
    }

});

//authenticate input against database documents
UserSchema.statics.authenticate = function(email, password, callback) {
    User.findOne({ email: email })
        .exec(function(error, user) {
            if (error) {
                return callback(error);
            } else if (!user) {
                var err = new Error('User not found.')
                err.status = 401;
                return callback(err);
            }
            bcrypt.compare(password, user.password, function(error, result) {
                if (result === true) {
                    return callback(null, user);
                } else {
                    return callback();
                }
            })
        });
}

//hash password before saving to database
UserSchema.pre('save', function(next) {
    var user = this;
    bcrypt.hash(user.password, 10, function(err, hash) {
        if (err) {
            next(err);
        }
        user.password = hash;
        next();
    });
}, function(next) {
    var user = this;
    userCounter.findByIdAndUpdate({ _id: 'entityId' }, { $inc: { seq: 1 } }, function(error, counter) {
        if (error)
            return next(error);
        user._id = userCounter.seq;
        next();
    });
});



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

module.exports = User; 

并创建带帖子的路线

var express = require('express');
var User = require('../models/user’);
// POST /register
router.post('/register', function(req, res, next) {
    if (req.body.email &&
        req.body.name &&
        req.body.password &&
        req.body.confirmPassword) {

        // confirm that user typed same password twice
        if (req.body.password !== req.body.confirmPassword) {
            var err = new Error('Passwords do not match.')
            err.status = 400;
            return next(err);
        }

        // create object with form input 
        var userData = {
            email: req.body.email,
            name: req.body.name,
            password: req.body.password
        };

        //use schema's 'create' method to insert document into Mongo
        User.create(userData, function(error, user) {
            if (error) {
                return next(error);
            } else {
                return res.redirect('/login');
            }
        });

    } else {
        var err = new Error('All fields required.')
        err.status = 400;
        return next(err);
    }
});

1 个答案:

答案 0 :(得分:0)

什么不能正常工作?
正如我在您的代码中看到的那样,当使用findByIdAndUpdate时,您缺少“{new:true}”,这意味着返回更新的模型而不是已存在的模型:

....
userCounter.findByIdAndUpdate({ _id: 'entityId' }, { new: true, $inc: { seq: 1 } }, function(error, counter) {
....

你可以查看这个答案:
Mongoose findByIdAndUpdate not returning correct model