我收到此错误:尝试将数据插入数据库时,“无法读取未定义的属性'插入'”。错误显示在:
db.coordinates。插入({“ 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的新手,如果您以复杂的方式讲出答案,我可能会不明白:)
如果您要monk
用于项目,则可以删除该mongodb
模块,因为它的功能已由和尚包装。根据Monk的文档,您应该执行以下操作:
const monk = require('monk');
const db = monk('localhost:27017/node5')
const coordinates = db.get('coordinates');
既然您已经有了对坐标集合的引用,则可以在以后的代码中使用它:
coordinates.insert({ x: data.x, y: data.y });
我希望这很容易理解。如果仍然令人困惑,请在下面发表评论,我将进一步详细说明:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句