0

大家好,我对 mongodb、mongoose 和 node.js 很陌生。我想创建一个小演示来看看猫鼬是如何工作的。在安装(并测试了 node.js 的正确性)之后,我下载了 mongoose 并尝试了以下代码(也在 mongoose 网站上提供):

require.paths.unshift('vendor/mongoose');
var mongoose = require('mongoose').Mongoose;

mongoose.model('User', {

properties: ['first', 'last', 'age', 'updated_at'],

cast: {
  age: Number,
  'nested.path': String
},

indexes: ['first'],

setters: {
    first: function(v){
        return this.v.capitalize();
    }
},

getters: {
    full_name: function(){ 
        return this.first + ' ' + this.last 
    }
},

methods: {
    save: function(fn){
        this.updated_at = new Date();
        this.__super__(fn);
    }
},

static: {
    findOldPeople: function(){
        return this.find({age: { '$gt': 70 }});
    }
}

});

var db = mongoose.connect('mongodb://localhost/db');

var User = db.model('User');

var u = new User();
u.name = 'John';
u.save(function(){
sys.puts('Saved!');
});

User.find({ name: 'john' }).all(function(array){

});

问题是当我运行 node myfile.js 时出现以下错误:

node.js:181
    throw e; // process.nextTick error, or 'error' event on first tick
    ^
Error: Cannot find module 'mongoose'
at Function._resolveFilename (module.js:320:11)
at Function._load (module.js:266:25)
at require (module.js:364:19)
at Object.<anonymous> (/my/path/to/mongoose+node test/myfile.js:2:16)
at Module._compile (module.js:420:26)
at Object..js (module.js:426:10)
at Module.load (module.js:336:31)
at Function._load (module.js:297:12)
at Array.<anonymous> (module.js:439:10)
at EventEmitter._tickCallback (node.js:173:26)

现在,我不得不再说一遍,我真的是新手,所以我的名为“mongoose+node test”的文件夹只有在 mongoose 文件夹中,其中包含一堆 JavaScript 文件,当然还有 myfile.js。我可能错过了什么吗?

4

2 回答 2

3

它找不到猫鼬。解决这个问题的最简单方法是通过npm.

安装 npm:

curl http://npmjs.org/install.sh | sh

要安装猫鼬:

npm install mongoose

您还必须下载并安装 mongoDB 并启动 mongoDB 服务器。

它将帮助您安装、unix quickstart运行和测试 mongoDB。

您的主要问题是require.paths不应编辑。您应该直接要求一个 url 或通过一个包系统。在nodejs 文档中,它指出require.paths应该避免。

就个人而言,我建议您坚持,npm因为它是分解标准。

于 2011-04-23T10:03:24.947 回答
1

在新版本中,您不需要使用.Mongoose.

只需替换以下内容:

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

和:

var mongoose = require('mongoose')

于 2011-04-23T10:10:59.063 回答