2/3更新后,猫鼬崩溃

时间:2015-08-28 16:59:58

标签: node.js mongodb mongoose

据我了解,对于正确的RESTfull API,您应该为每个要更新的文档发送单独的请求。

在这种情况下,我正在处理用户导入功能。它正确地解析了前两个用户,但在第三个用户上失败了。

这些请求使用Restangular使用forEach发送,该forEach迭代应导入的用户数组。

功能:

    /** ----------------------------------- *
     * importUser
     * @param req
     * @param res
     * ------------------------------------ */
    function importUser(req, res) {

        var data = req.body,
            User = new models.User({}),
            user = {},
            ObjectId = require('mongoose').Types.ObjectId;
        var usrId = new ObjectId( (typeof data.id !== 'undefined' && data.id.length < 12) ? "123456789012" : data.id );

        user.firstname = data.firstname;
        user.lastname = data.lastname;
        user.email = data.email.toLowerCase();

        var pass = new models.Passport({});
        pass.provider = "local";
        pass.token = "";
        pass.makeSalt();
        pass.hashedPassword = pass.encryptPassword(data.password);

        user.passports = pass;

        User.update( { 'email':user.email}, user,{ upsert : true }, function(err,docs){
                if(err) {
                    res.status(400).send(new UserError('INVALID_USER_DATA'));
                }else {
                    res.send(docs);
                }
            }
        );
    }

日志:

Mongoose: users.findOne({ _id: ObjectId("55d72ccc409102491250a5db") }) { fields: undefined }  
Mongoose: users.findOne({ _id: ObjectId("55d72ccc409102491250a5db") }) { fields: undefined }  
Mongoose: users.findOne({ _id: ObjectId("55d72ccc409102491250a5db") }) { fields: undefined }  
Mongoose: users.update({ _id: ObjectId("55e08d5589dcd76226d32efd") }) { '$set': { email: 'smiley86@gmail.com' } } { passports: { hashedPassword: 'AsxcJSxIH7wZ+IF3I+X6BZiPKtgqIzxA5KgnmSLpVgPhzRtE1apxD1i6EqXFDxOpO1kvMiVWtkrW8doH2KxrJg==', salt: 'YreiOZjcVoAtmqUbZV7YVg==', token: '', provider: 'local', id: '55e08d5789dcd76226d32efe', obj_type: 'passport' }, email: 'smiley86@gmail.com', lastname: 'Hedin', firstname: 'Mikael' } 
Mongoose: users.update({ _id: ObjectId("55e08d5789dcd76226d32eff") }) { '$set': { email: 'john.doe@exempel.se' } } { passports: { hashedPassword: '1Pw6KjikpmrhH9CWlNZCeDbZWcOTI5y57oK/qW0tu04h2nmN/cUIcyJdl8nwYdVFKXO3rf2do1eN89FeQcfV6g==', salt: 'qOdXvaszh2wtx6oBPkUORw==', token: '', provider: 'local', id: '55e08d5789dcd76226d32f00', obj_type: 'passport' }, email: 'john.doe@exempel.se', lastname: 'Doe', firstname: 'John' } 
/Users/mikael/Sites/api-server-models/node_modules/mongoose/lib/query.js:2001
  oldCb(error, result ? result.result : { ok: 0, n: 0, nModified: 0 });
  ^
TypeError: object is not a function
at Query.callback (/Users/mikael/Sites/api-server-models/node_modules/mongoose/lib/query.js:2001:7)
at /Users/mikael/Sites/api-server-models/node_modules/mongoose/node_modules/kareem/index.js:177:19
at /Users/mikael/Sites/api-server-models/node_modules/mongoose/node_modules/kareem/index.js:109:16
at process._tickCallback (node.js:355:11)

req.body:

{ firstname: 'Mikael',lastname: 'Hedin', password: 'mikael', email: 'smiley86@gmail.com', organization: 'Runic Design', token: '<JSON JWT token for authentication>' }

new models.User({}):

{ passports: [], status: 2, telephone: [], obj_type: 'user' }

UserSchema(在model.User({})中检索):

UserSchema.add({
    firstname: {
        type: String,
        required: true
    },
    lastname: {
        type: String,
        required: true
    },
    email: {
        index: {unique: true},
        type: String,
        required: true,
        validate: [validateEmail, 'INVALID_USER_EMAIL']
    },
    telephone:[TelephoneSchema],
    organization: {
        type: String
    },
    status: {
        type: Number,
        min: 0,
        max: 3,
        default: 2
        /*
         * 0 - removed
         * 1 - deactivated
         * 2 - draft/uncomfirmed
         * 3 - activated
         */
    },
    passports: [PassportSchema],
    expDate:{
        type: Date
    },
    loginAt:{
        type: Date
    }
});

我不能为我的生活弄清楚为什么它会在最后一次请求中抛出这个错误......他们都是相同的

1 个答案:

答案 0 :(得分:0)

如果你正在使用mongoose,你应该定义你的文章或对象,因为使用mongoose的目的是将对象数据模型正确地传递给你的数据库。

我有类似的代码,但结构不同:

我的 User.js 对象数据模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model
module.exports = mongoose.model('User', new Schema({
    _id : {type : String, unique : true},
    username: String,
    email : String,
    password: String,
    gcmID :String,
    gender : String
}));

这是调用用户对象模型时的代码:

var User  = require('../model_data/User');

var register = {

    registergcmSecond : function (req,res){
        //get id req.body to a variable and check it one by one
        var gcmID  = req.body.gcmID || '';
        var uidUser = req.body.uidUser || '';
        //check your your variable to make sure is not null
        if(gcmID &&uidUser){
            User.update({ _id : uidUser },{gcmID : gcmID}, function (err, user){
                if(err){
                    res.json({
                        status : "not_ok",
                        result : "Failed query",
                        resultType : serverConst.ErrorQuery
                    });
                }else{
                    res.json({
                        status : "ok",
                        result : "Document Updated",
                        resultType : serverConst.RegisterGcm
                    });
                }

            });
        }
    }
}

如果您遇到困难并且不知道结构是什么样的,您可以访问此网站:http://thejackalofjavascript.com/architecting-a-restful-node-js-app/