尝试将数据插入数据库时,出现此错误:“无法读取未定义的属性‘插入’”。错误显示在:
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的新手,如果你以复杂的方式说出答案,我可能无法理解:)
最佳答案
如果您的项目使用 monk
,那么您可以删除 mongodb
模块,因为它的功能已被 Monk 封装。来自 Monk's documentation ,你应该这样做:
const monk = require('monk');
const db = monk('localhost:27017/node5')
const coordinates = db.get('coordinates');
现在您已经有了对坐标集合的引用,您可以稍后在代码中使用它:
coordinates.insert({ x: data.x, y: data.y });
我希望这很容易理解。如果仍然令人困惑,请在下面发表评论,我将进一步详细说明:)
关于javascript - 尝试将数据放入 MongoDB 时无法读取未定义的属性 'insert',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623401/