我正在尝试将mongoDB合并到我的应用程序中,但是当我尝试添加到一个集合时,我收到错误'无法读取'插入'尝试使用nodeJS启动服务器时未定义。
我很感激以前曾经问过这个问题,但是当我尝试通过编写下面的代码来解决这个问题时,我试图纠正错误,但是我没有定义var
;
var accountCollection = var mongodb = mongodb.collection('account');
accountCollection.insert({username:"wendy3", password:"lilac3"});
我的服务器的相关代码如下,我在网上看了很多指南,似乎没有解决我的问题,所以任何帮助都将不胜感激。
//create server, listening on port 3000
//when there is a request to port 3000 the server is notified
//depending on the request a specific action will be carried out
var mongodb = require("mongodb");
//create connection to MongoDB
var db = mongodb('localhost:27017/Game', ['account', 'progress']);
//insert into collection
db.account.insert({username:"wendy3", password:"lilac3"});
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var colors = require('colors/safe');
答案 0 :(得分:2)
与数据库的连接是异步操作,但您尝试访问它,就好像它是同步的一样。
如果您查看正在使用的软件包的examples,则表明您必须使用一个回调函数,一旦收到连接响应就会调用该函数:
var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'localhost:27017/Game';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if (err) return console.log('Error: ' + err);
console.log("Connected correctly to server");
});
答案 1 :(得分:0)
谢谢 - 我想我现在明白了(我是MongoDB的新手,所以请原谅我)
我现在有以下代码;但是我收到错误invalid schema, expected mongodb.
我是否可以在某处MongoClient
代替mongodb
?所以我可以看到它正在尝试连接,但回调是返回错误。
代码:
var MongoClient = require('mongodb').MongoClient;
//connection url
var url = ('localhost:27017/Game', 'account', 'progress');
//use connect method to connect to server
MongoClient.connect(url, function(err, db){
if (err) return console.log('Error: ' + err);
console.log('mongodb is connected to the server');
});