在尝试将数据放入MongoDB时,无法读取未定义的属性“insert”

时间:2017-01-12 21:35:33

标签: javascript node.js mongodb mongoose

我收到此错误:“尝试将数据插入数据库时​​,无法读取未定义的属性'insert'。错误显示在:

db.coordinates。 insert ({“x”:“data.x”,“y”:“data.y”})

数据库名称 - “node5” 集合名称 - “坐标”

// Including libraries
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var static = require('node-static'); // for serving files

//db connection

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/node5');



var url = 'mongodb://localhost:27017/node5';
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server.");
  db.close();
});

// This will make all the files in the current folder
// accessible from the web
var fileServer = new static.Server('./');

// This is the port for our web server.
// you will need to go to http://localhost:8080 to see it
app.listen(8080);

// If the URL of the socket server is opened in a browser
function handler(request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
}

// Delete this row if you want to see debug messages
io.set('log level', 1);


// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {
    // Listen for mouse move events
    socket.on('post', function (data) {
        console.log('posted');
        console.log(data);
        socket.broadcast.emit('posted', data); // Broadcasts event to everyone except originating client
        db.coordinates.insert({ "x" : "data.x", "y" : "data.y"})
    });
});

在写答案时,请注意我是node.js的新手,如果你以复杂的方式说出答案我可能不明白:)

1 个答案:

答案 0 :(得分:0)

如果您正在为项目使用monk,那么您可以删除mongodb模块,因为它的功能正在被和尚包裹。从Monk's documentation开始,您应该执行以下操作:

const monk = require('monk');
const db = monk('localhost:27017/node5')

const coordinates = db.get('coordinates');

现在您已经引用了 coordinates 集合,您可以稍后在代码中使用它:

coordinates.insert({ x: data.x, y: data.y });

我希望这很容易理解。如果它仍然令人困惑,那么请在下面评论,我将进一步阐述:)