无法将数据插入mongodalab集合

时间:2016-02-15 16:16:38

标签: node.js mongodb

我刚开始使用Node.JS,尝试连接到MongodbLab,我按照文档http://docs.mongolab.com/#connect 但是无法在我的集合“团队”中插入任何数据错误继续说TypeError:无法读取未定义的属性'insert',我谷歌2小时,请帮助。

var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

var mongoose = require('mongoose');
var uri = "mongodb://awei:RRRRR@ds061365.mongolab.com:61365/aweitest";
mongoose.createConnection(uri);
 // we're connected!
 var db = mongoose.connection;
 db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
 db.once('open', function() {

  });

db.team.insert({ "name" : "Awei" });

错误

c:\Users\awei\WebstormProjects\untitled\app.js:22
db.team.insert({ "name" : "Awei" });
      ^

TypeError: Cannot read property 'insert' of undefined
at Object.<anonymous> (c:\Users\awei\WebstormProjects\untitled\app.js:22:8)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3

Process finished with exit code 1

2 个答案:

答案 0 :(得分:1)

您可以使用mongoose connection的db对象访问不使用模型的预先存在的集合,如下所示:

var uri = "mongodb://awei:RRRRR@ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
var conn = mongoose.connection,
    db = conn.db;
conn.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
conn.on('open', function() {
    console.log("mongodb is connected!!");
    db.collection("team", function (err, collection) {
        collection.insert({ "name" : "Awei" }, function(err, result){
            console.log(result);
        });
    });
});

答案 1 :(得分:1)

从我所看到的,您需要使用用户名和密码进行连接。见:

http://docs.mongolab.com/connecting/

在&#34;查找数据库连接信息&#34;。

此外,MongoLab还提供了Node.js的入门帮助:

http://docs.mongolab.com/languages/

实际连接到数据库后,您应该能够将数据插入到团队集合中。