2

您好:我是 Node/Mongo/Express 等的新手,并试图通过 mongoose 建立与 mongodb 的简单连接。此时我只是试图建立连接但收到错误:

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
ReferenceError: mongoose is not defined
    at Object.<anonymous> (/Users/mattydorey/Code/napkin_0.1/testdb.js:8:1)
    at Module._compile (module.js:407:26)
    at Object..js (module.js:413:10)
    at Module.load (module.js:339:31)
    at Function._load (module.js:298:12)
    at Array.<anonymous> (module.js:426:10)
    at EventEmitter._tickCallback (node.js:126:26)

任何帮助深表感谢。这是我的代码:

// Launch express and server
var express = require('express');
var app = express.createServer();

//connect to DB
var moongoose = require('/Users/me/node_modules/mongoose').Mongoose;
var db = mongoose.connect('mongodb://localhost/napkin_0.1');

//Configure Node w/ Dependencies
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(require("stylus").middleware({
      src: __dirname + "/public",
      dest: __dirname + "/public",
      compress: false
    }));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  //app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Define Model
mongoose.model('User', {
  collection: 'user',
  properties: [
    'created',
    'username',
    'password',
    'email'
  ],
  indexes: [
    'created',
    [{username: 1},{unique: true}],
    [{email: 1},{unique: true}]
  ],
  static: {},
  methods: {},
  setters: {},
  getters: {}
  }
);

//Define Collection
var User = db.model('User');

// Handle Data
var user = new User();
user.created = new Date();
user.username = "TEST";
user.password = "PASS";
user.email = "someemail";
user.save();

//Launch Server
app.listen(3002);
4

2 回答 2

8

并检查所需路径,尝试:

var mongoose = require('mongoose').Mongoose;
var db = mongoose.connect('mongodb://localhost/napkin_0.1');
于 2011-06-12T08:55:32.217 回答
1

尝试这个

const mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/napkin_0.1')
于 2020-10-08T11:23:35.157 回答