使用Nodejs到MongoDb的数据插入不起作用

我试图插入数据与Nodejs,并且有我的插入代码有问题。 它连接到数据库很好,但不插入数据。

这是我的server.js:

var mongo = require('mongodb').MongoClient global.db = null var sDatabasePath = 'mongodb://localhost:27017/kea' global.mongoId = require('mongodb').ObjectID /**************************************************/ var student = require(__dirname + '/student.js') /**************************************************/ mongo.connect(sDatabasePath, (err, db) => { if (err) { console.log('ERROR 003 -> Cannot connect to the database') return false } global.db = db console.log('OK 002 -> Connected to the database') return true }) 

这是我的student.js:

 var student = {} /**************************************************/ student.saveStudent = (fcallback) => { var jStudent = { "firstName": "Sarah", "lastName": "Jepsen", "age": 27, "courses": [ { "courseName": "Web-development", "teachers": [ { "firstName": "Santiago", "lastName": "Donoso" } ] }, { "courseName": "Databases", "teachers": [ { "firstName": "Dany", "lastName": "Kallas" }, { "firstName": "Rune", "lastName": "Lyng" } ] }, { "courseName": "Interface-Design", "teachers": [ { "firstName": "Roxana", "lastName": "Stolniceanu" } ] } ] } global.db.collection('students').insertOne(jStudent, (err) => { if (err) { var jError = { "status": "error", "message": "ERROR -> student.js -> 001" } console.log(jError) return fcallback(true, jError) } var jOk = { "status": "ok", "message": "student.js -> saved -> 000" } console.log(jOk) return fcallback(false, jOk) }) } module.exports = student 

在控制台中,我只能得到数据库连接消息,即'OK 002 – >连接到数据库'。 我不会找回来自user.js文件的jError或jOk消息。

你的函数不会调用插入函数,需要调用saveStudent方法来保存函数。

 var mongo = require('mongodb').MongoClient global.db = null var sDatabasePath = 'mongodb://localhost:27017/kea' global.mongoId = require('mongodb').ObjectID /**************************************************/ var student = require(__dirname + '/student.js') /**************************************************/ mongo.connect(sDatabasePath, (err, db) => { if (err) { console.log('ERROR 003 -> Cannot connect to the database') return false } global.db = db console.log('OK 002 -> Connected to the database'); /*==================== Call the save function ==================*/ //call the saveStudent to insert entry in database student.saveStudent( ( err , resp ) => { //your callback function console.log("handle callback"); }); /*======================================*/ return true })