gpt4 book ai didi

node.js - 无法读取未定义的属性 'insert'

转载 作者:可可西里 更新时间:2023-11-01 09:57:01 26 4
gpt4 key购买 nike

这是我第一个使用 Mongo 数据库的 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'));
});

我在尝试将值插入数据库时​​收到错误无法读取未定义的属性“插入”。我在这里错过了什么吗?有人可以帮帮我吗?

最佳答案

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

var db= mongo.collection('user');

db.user.insert({"username": email,
...

该集合没有名为 user 的属性,因此对其调用 insert 会导致错误。

我相信你想这样做:

var userCollection = var db= mongo.collection('user');

userCollection.insert({"username": email,
...

关于node.js - 无法读取未定义的属性 'insert',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33211113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com