queryselector必须是一个对象mongodb

时间:2017-05-18 02:47:39

标签: javascript node.js mongodb express

我尝试在db中发布数据,但是我收到此错误queryselector must be an object mongodb。这是我的代码

模型     var MongoClient = require(' mongodb')。MongoClient;

exports.register = function(val,cb) {
    var email = val['email'];
    var password = val['password'];
    var user  = val['user'];
    MongoClient.connect(//url connect to db  ,function(err,db){
        if(err)
            cb(null,{result:false,message:err});
        db.collection('user').findOne(email,function(err,user){
            if(err)
                cb(null,{result:false,message:err});
            if(user){
                cb(null,{result:false,message:'Email already exists'});
            }else{
                db.collection('user').insert(user,function(err){
                    if(err)
                        cb(null,{result:false,message:err});
                    cb(null,{result:true,message:'Success'});
                })
            }
        })
    });
};

控制器

var express= require('express');
var router = express.Router();
var user = require('../models/register');

router.post('/',function(req,res) {
    var val =[];
    val['email'] = req.body.email;
    val['password'] = req.body.password;
    val['user']={
        email:req.body.email,
        password:req.body.password
    }

    user.register(val,function(err,data){
        if(err)
            console.log(err)
        res.json(data);
    })

});

module.exports = router;

我尝试更改为val={}但不行。我哪里错了?请帮帮我

1 个答案:

答案 0 :(得分:1)

应该是......

 exports.register = function(val,cb) {
        var email = val['email'];
        var password = val['password'];
        var user  = val['user'];
        MongoClient.connect(//url connect to db  ,function(err,db){
            if(err)
                cb(null,{result:false,message:err});
            db.collection('user').findOne({email:email},function(err,user){
                if(err)
                    cb(null,{result:false,message:err});
                if(user){
                    cb(null,{result:false,message:'Email already exists'});
                }else{
                    db.collection('user').insert(user,function(err){
                        if(err)
                            cb(null,{result:false,message:err});
                        cb(null,{result:true,message:'Success'});
                    })
                }
            })
        });
    };