无法读取属性'插入'未定义的

时间:2015-10-19 09:35:05

标签: node.js mongodb express

这是我使用Mongo db的第一个Node.js程序。这是我的代码:

/ **  *模块依赖性。  * /

 var express = require('express')
 , routes = require('./routes')
 , user = require('./routes/user')
 , http = require('http')
 , path = require('path');
 var mongo = require("./routes/mongo");
 var session = require('express-session');
 var MongoClient = require('mongodb').MongoClient;
 var assert = require('assert');

 var monStore=require("connect-mongo")(session);
 var url = 'mongodb://localhost:27017/session';


 var app = express();

 app.configure(function(){
   app.set('port', process.env.PORT || 4000);
   app.set('views', __dirname + '/views');
   app.set('view engine', 'ejs');
   app.use(express.favicon());
   app.use(express.logger('dev'));
   app.use(express.bodyParser());
   app.use(express.methodOverride());
   app.use(app.router);
   app.use(express.static(path.join(__dirname, 'public')));
 });

 app.configure('development', function(){
   app.use(express.errorHandler());
 });

 app.get('/', routes.index);
 app.get('/users', user.list);
 app.post('/signup',function(req,res){
var email=req.param("email");
var fname=req.param("firstname");
var lname=req.param("lastname");
var password=req.param("password");
var url1="mongodb://localhost:27017/signup";
mongo.connect(url1, function(){
var db= mongo.collection('user');

db.user.insert({"username": email,
                "password":password,
                "firstname":fname,
                "lastname":lname});

res.render("login",{title:"welcome"});
 });
 });

 app.post('/login',function(req,res){
    var email=req.param("email");
var password=req.param("password");
var url1="mongodb://localhost:27017/login";;
mongo.connect(url1, function(){
var db= mongo.collection('signup');
db.findOne({username: email, password:password}, function(err,user){
    console.log(user.email);
    if(user)
        {
        res.render("welcome");
        }
    else
        {
        res.render("login",{title:"ivalid"});
        }
});
});
 });

 MongoClient.connect(url, function() {

  console.log("Connected correctly to server.");

});
 http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
 });

我收到错误无法读取属性'插入'我在尝试将值插入数据库中的undefined。我在这里错过了一些观点吗?有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:8)

您正在使用foreach变量作为对集合的引用:

db

该集合没有名为 user 的属性,因此在其上调用var db= mongo.collection('user'); db.user.insert({"username": email, ... 会导致错误。

我相信你想这样做:

insert