我通过 npm 安装了 mongodb
npm install mongodb
其中安装了1.4.32版本的mongodb驱动。底部给出的代码运行良好,但是当我升级我的驱动程序(并从节点模块中删除 1.4.32 的旧文件夹,更新 package.json)时,我收到以下错误:
unknown system error : 10042.
我在搜索引擎上查了一下,它是一个 windows winsock 错误,不知道为什么我用最新版本得到这个,但用早期版本却没有..
我猜它与url中的replicaSet选项有关,我不知道如何设置它,我的意思是我试过了
mongodb://localhost/test?replicaSet=rs0-1
但是,我们只需要配置一个副本集,我们如何使用 null 作为副本集..
这是我在 nodeJS 中使用的连接代码,它适用于 1.4.* 的 mongodb 本机驱动程序,但不适用于 2.0.18 的 mongodb 本机驱动程序。
var express = require('../Express2/node_modules/express');
var app = express(); // instantiate the express object thru its constructor
var path = require('path');
var assert = require('assert');
var mongodb = require('mongodb'); // 2.0.18
// use /public directory for serving web pages first
app.use(express.static(path.join(__dirname , '/public'))); // add current directory
// when a request for /insert is received
app.get("/insert",function(req,resp){
// Create a mongo client
var mongoClient = mongodb.MongoClient;
// configure url to connect to
var url = 'mongodb://localhost:27017/test';
//mongodb://user:pass@ipaddr:port/dbname
// try to connect and get db handle
mongoClient.connect(url,function(err,db){
if(err){
console.log(err.toString()); // Error thrown here..
}
else{
console.log('successfully connected to mongod server');
var collectionStudent = db.collection('student');
// accepts obj and callback.
collectionStudent.insert(
{name:'Andrew',courses:[{subject:'RDBMS',fee:15000}]},
function(err,result){
resp.send('Result of insertion:' + JSON.stringify(result));
resp.end();
db.close();
}
);
}
});
});
// for pages not found in public directory, do this:
app.get("*",function(req,resp){
resp.sendFile(path.join(__dirname , "/public/404.html"));
});
// any other special routes like /result etc appear below this line
//..
//..
app.listen(3000);