为什么Node的mongoose告诉我undefined不是一个函数?

时间:2016-07-30 23:25:08

标签: javascript node.js mongodb mongoose

我正在尝试创建一个Node脚本,该脚本将连接到外部服务器的MongoDB并插入用户。我在几十个使用localhost的教程中找到的基本内容。出现的问题是,在遵循这些教程时,无论我尝试过什么,我似乎都会遇到TypeError:undefined不是函数消息。我知道这是因为我对Mongo和Node都不熟悉,但遗憾的是我知道这并不容易弄明白。

我所拥有的代码没有涉及任何网页,在这种情况下应该是后端连接。代码如下:

    var User = require('/var/www/html/testing/folder1/User.js');
    var mongoose = require('mongoose');
    mongoose.Promise = global.Promise;


    mongoose.connect('mongodb://root:(Server Admin Password)@(I.P address of the server)/(Database Name)');

    var newUser = User({
      _id: "KM529",
      email: "emailname@email.com",
      name: "John Smith",
      password: "password",
      photo: "a picture url"
    });

    newUser.save(function(err){
      if(err){
        console.log(err);
        throw err;
      }

      console.log('User save successfully');
    });

以上是实际运行的文件。附加的所需文件是:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;

    // Creates a schema to be used for all user documents
    var userSchema = new Schema({
      _id: { type:String, required: true, unique: true },
      email: { type: String, required: true, unique: true },
      name: { type: String, required: true },
      password: { type: String, required: true} ,
      photo: String,
    });

    var User = mongoose.model('User', userSchema);

    module.exports = User;

我已经查看过15个类似的stackoverflow问题,但是没有一个能让我解决这个问题。如果有人能指出我正确的方向,我将永远感激。

编辑:我得到的错误是:

    /var/www/html/testing/pokemon/node_modules/mongoose/lib/connection.js:282
      var promise = new Promise.ES6(function(resolve, reject) {
            ^
    TypeError: undefined is not a function
at NativeConnection.Connection.open (/var/www/html/testing/pokemon/node_modules/mongoose/lib/connection.js:282:17)
at Mongoose.connect (/var/www/html/testing/folder1/node_modules/mongoose/lib/index.js:241:47)
at Object.<anonymous> (/var/www/html/testing/pokemon/test.js:8:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

1 个答案:

答案 0 :(得分:2)

使用节点repl进行了一些调试:

> var m = require('mongoose')
undefined
> m.Promise
{ [Function: Promise] ES6: [Function], SUCCESS: 'complete', FAILURE: 'err' }
> m.Promise.ES6
[Function]
> global.Promise
[Function: Promise]
> global.Promise.ES6
undefined

global.Promise.ES6使用节点6.2.2

不存在

删除此行:

mongoose.Promise = global.Promise;