使用node.js插入MongoDB的键错误对于某些没有包含点的键的对象会失败?

时间:2014-05-22 03:01:13

标签: javascript node.js angularjs mongodb

我有一个使用 Angular JS 绑定的网络表单,并通过POST调用我的服务器代码中的路由,通过使用mongodb连接将路由到MongoDB收集

我想要插入的对象是一个有效的Java Script对象,实际上,有时它只是插入ok,但有时Mongo会抱怨一个键包含一个点。

这是Angular控制器内的AJAX调用(这总是要经历):

$.ajax({
    type:"POST",
    url:"/psychos",
    data:JSON.stringify(this.psycho)                
})

这是路线处理代码:

app.post("/psychos", function(request, response) {

    var psychologist = request.body
    console.log("We got via AJAX\n"+JSON.stringify(psychologist, undefined, 2))

    psicologosCollection.insert(psychologist, function(error, responseFromDB) {

        if (error) {

            console.log(error)
            response.send(responseFromDB)
        }

        else {
                console.log("Se ha insertado: "+ JSON.stringify(responseFromDB))
                response.send(responseFromDB)
        }

    })
})

我的服务器代码管理Passport身份验证,并且在MongoDB连接时定义了rotue。

这是我的整个服务器代码:

var express     =       require('express')
var mongodb     =       require('mongodb')
var mongoose    =       require('mongoose')
var bodyParser  =       require('body-parser')
var cookie      =       require('cookie-parser')
var connect     =       require('connect')
var passport    =       require('passport')
//var flash         =       require('connect-flash')
var session     =       require('express-session');
var MongoStore  =       require('connect-mongo')(session);
var LocalStrategy =     require('passport-local').Strategy;

var app = express()

var BSON = mongodb.BSONPure

app.use(express.static(__dirname+"/public"))
app.use(bodyParser())
app.use(cookie())
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' })); 
app.use(passport.initialize());
app.use(passport.session());
//app.use(flash())

var MongoDBClient = mongodb.MongoClient

mongoose.connect('mongodb://localhost/psicologosTuxtepecDB')



var Schema = mongoose.Schema
var userCredential = new Schema({

    username:   String,
    password:   String

},  {
    collection:     'members'
})

var userCredentials = mongoose.model('members', userCredential)



app.use(session({
    secret: 'ziKologiia',
    clear_interval: 900,
    cookie: { maxAge: 2 * 60 * 60 * 1000 },
    store: new MongoStore({
      db : mongoose.connection.db
    })
  }));


passport.serializeUser(function(user, done) {
  done(null, user);
})

passport.deserializeUser(function(user, done) {
  done(null, user);
})

passport.use(new LocalStrategy(function(username, password, done) {
  process.nextTick(function() {
    userCredentials.findOne({
      'username': username, 
    }, function(err, user) {
      if (err) {
        return done(err);
      }

      if (!user) {
        return done(null, false);
      }

      if (user.password != password) {
        return done(null, false);
      }

      return done(null, user);
    });
  });
}));

MongoDBClient.connect("mongodb://localhost/psicologosTuxtepecDB", function (error, psicologosTuxtepecDB) {

    if (error) {

        console.log("We've got a connection error, so far we should take this function better for a correct debug")
    }

    else {

        console.log("Connection to psicologosTuxtepecDB has been successful")

        var psicologosCollection = psicologosTuxtepecDB.collection("psychologists")



        app.get('/registro', function(request,response) { 
            if(request.isAuthenticated()) 
                response.sendfile("public/html/registro.html") 
            else 
                response.redirect('/')
        })

        app.post("/psychos", function(request, response) {

            var psychologist = request.body
            console.log(psychologist)

            psicologosCollection.insert(psychologist, function(error, responseFromDB) {

                if (error) {console.log(responseFromDB);response.send(responseFromDB)}

                console.log("Se ha insertado: "+ JSON.stringify(responseFromDB))
                response.send(responseFromDB)
            })
        })

        app.get("/psychos/:id", function(request, response) {

            var id = new BSON.ObjectID(peticion.params.id)

            psicologosCollection.findOne( 
                                            {'_id':id},
                                            function(error,responseFromDB) { if (error) {response.send(responseFromDB)} response.send(responseFromDB)}
                                        )
        })

        app.get("/psychos", function(request,response) {

            psicologosCollection.find().toArray(function(error,responseFromDB) {
                if (error) {response.send(responseFromDB)}
                response.send(responseFromDB)
            })
        })

        app.post('/login',
          passport.authenticate('local', {
            successRedirect: '/loginSuccess',
            failureRedirect: '/loginFailure'
          })
        )

        app.get('/loginFailure', function(req, res, next) {
            res.redirect('/')
        })


        app.get('/loginSuccess', function(req, res, next) {
          res.redirect('/registro')
        })      

        app.get('/logout', function (request, response){
          request.session.destroy(function (err) {
            response.redirect('/'); //Inside a callback… bulletproof!
          })
        })  

        app.listen(2311, function () {
            console.log("app escuchando en el puerto Maricela fecha de nacimiento DDMM")
        })
    }

})

以防我出示我的Angular JS文件:

(function() {


        var app = angular.module('PsicologosRegister', ['checklist-model'])

        app.controller('PsicologoController', function($scope) {

            this.psycho = psicologo

            this.print = function() {

                console.log(this.psycho)
            }

            this.toMongo = function() {
                $.ajax({
                    type:"POST",
                    url:"/psychos",
                    data:JSON.stringify(this.psycho)                
                })              
            }
        })

        app.controller('PersonalDataController', function() {

            this.data = datos_Personales

        })

        app.controller('ProfessionalDataController', function() {

            this.data = datos_Profesionales
        })

        app.controller('ProfessionalInterestsController', function() {

            this.data = intereses_Profesionales

            this.print = function() {

                console.log(this.psycho)
            }
        })              

        app.controller('PosgraduateController', function() {


            this.degrees = [

                            'Especialidad',
                            'Maestría',
                            'Doctorado'
            ]

            this.postgraduates = _postgraduates

            this.addPostgraduate = function() {

                this.postgraduates.push({})
            }



        })

        app.controller('WorkController', function() {

            this.works = _works

            this.addWork = function() {

                this.works.push("")
            }
        })      

        app.controller('FreelanceController', function() {

            this.freelances = _freelances

            this.addFreelance = function() {

                this.freelances.push("")
            }

            this.noFreelance = function() {
                this.freelances = [""]
            }
        })          

        app.controller('NoPsychoWorkController', function() {

            this.noPsychoWorks = _noPsychoWorks

            this.addNoPsychoWork = function() {

                this.noPsychoWorks.push("")
            }

            this.notNoPsychoWorks = function() {
                this.noPsychoWorks = [""]
            }           
        })  

        app.controller('TrainingTopicsController', function() {

            this.trainingTopics = _trainingTopics
            this.add = function() {
                this.trainingTopics.push("")
            }
        })

        app.controller('GroupsController', function() {

            this.groups = _groups

            this.add = function() {
                this.groups.push("")
            }

            this.doesntBelongToAnywhere = function() {
                this.groups = [""]
            }
        })      

        var _noPsychoWorks = [""]
        var _freelances = [""]
        var _works = [""]
        var _postgraduates = [{}]
        var _trainingTopics = [""]
        var _groups = [""]
        var _events = [{}]
        var datos_Personales = {}
        var datos_Profesionales = {postgraduates:_postgraduates, works: _works, freelances:_freelances, noPsychoWorks:_noPsychoWorks}
        var intereses_Profesionales = {events:_events,groups:_groups,trainingTopics:_trainingTopics}

        var psicologo = {

                            datosPersonales:            datos_Personales,
                            datosProfesionales:         datos_Profesionales,
                            interesesProfesionales:     intereses_Profesionales
        }
})()

实施例

这是一个失败的:

We got via AJAX
{
  "{\"datosPersonales\":{\"name\":\"Maricela\",\"lastname\":\"Aguilar\",\"age\":\"22\",\"phone\":\"2878710097\",\"mobile\":\"2878812505\",\"email\":\"af05_@hotmail.com\",\"address\":\"Carranza 168 Int 2\"},\"datosProfesionales\":{\"postgraduates\":": {
    "{\"degree\":\"Especialidad\",\"title\":\"Amor\",\"cedula\":\"ASFAS5\"},{\"degree\":\"Maestría\",\"title\":\"Romance\",\"cedula\":\"FAS15\"}],\"works\"": {
      "\"Universidad Hispano\"],\"freelances\"": {
        "\"Asociación Psicólogos\"],\"noPsychoWorks\"": {
          "\"\"],\"almaMater\":\"BUAP\",\"course\":\"1987\",\"cedula\":\"SAFS555FSA\",\"workAreas\"": {
            "\"Clínica\",\"Laboral\"],\"freelance\":\"true\",\"noPsychoWork\":\"false\"},\"interesesProfesionales\":{\"events\"": {
              "{}],\"groups\"": {
                "\"Asociación de Psicólogos de Tuxtepec\",\"Club de Toby\"],\"trainingTopics\"": {
                  "\"Real Madrid\",\"Cocina\"],\"activities\"": {
                    "\"Conferencias y encuentros\",\"Talleres\"],\"trainingAreas\"": {
                      "\"Educativa\"],\"belongsToSomewhere\":\"true\",\"hasParticipated\":\"true\",\"wantsToBelong\":\"true\",\"whyToBelong\":\"Futuro\"}": ""
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
[Error: key {"datosPersonales":{"name":"Maricela","lastname":"Aguilar","age":"22","phone":"2878710097","mobile":"2878812505","email":"af05_@hotmail.com","address":"Carranza 168 Int 2"},"datosProfesionales":{"postgraduates": must not contain '.']

这是一个有效的工作:

We got via AJAX
{
  "{\"datosPersonales\":{\"name\":\"Pepe\",\"lastname\":\"Guitérrez Javier\",\"age\":\"8755\",\"phone\":\"2252\",\"mobile\":\"555\"},\"datosProfesionales\":{\"postgraduates\":": {
    "{}],\"works\"": {
      "\"UYAQ\"],\"freelances\"": {
        "\"AFSFSA\"],\"noPsychoWorks\"": {
          "\"fsafas\",\"fsad\",\"fasd\"],\"almaMater\":\"BUAP\",\"course\":\"1998\",\"cedula\":\"FSA44\",\"workAreas\"": {
            "\"Clínica\",\"Social\"],\"freelance\":\"true\",\"noPsychoWork\":\"true\"},\"interesesProfesionales\":{\"events\"": {
              "{}],\"groups\"": {
                "\"fdsfds\"],\"trainingTopics\"": {
                  "\"dsfds\",\"fds\"],\"activities\"": {
                    "\"Conferencias y encuentros\",\"Talleres\"],\"trainingAreas\"": {
                      "\"Social\"],\"belongsToSomewhere\":\"true\",\"hasParticipated\":\"true\",\"wantsToBelong\":\"true\",\"whyToBelong\":\"fdsfds\"}": ""
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

什么是不应该获得.

1 个答案:

答案 0 :(得分:0)

我不确定,也没有时间深入挖掘您的代码,但mongo db写入失败有时与写入问题有关:http://docs.mongodb.org/manual/core/write-concern/

希望这有帮助。