【发布时间】:2021-12-19 16:39:21
【问题描述】:
我想要一个环境,让我能够牢牢掌握 CRUD 操作的工作原理。到目前为止,我一直在使用views 来查看数据的外观,但由于明显的不灵活,这种方法并不是那么有洞察力——就像在黑暗中驾驶一样。
现在我希望能够通过 Mongoose 提供的功能来处理 MongoDB 中的数据,这样我就可以看到当我这样做或那样做时实际发生了什么,子文档,人口,诸如此类的东西。最初,我在script.js 文件中有这段代码:
var mongoose = require('mongoose');
// ...
// define schemas
// try some crazy things
// ...
console.log(results);
然后我尝试执行该代码:
node script.js
这没有用。然后我尝试了:
mongo load('script.js')
这一次,我得到了一个错误,当然——require() 没有定义。掌心。
希望这能让您了解我正在尝试做什么。从那以后,我尝试了其他似乎不起作用的方法。
请指教。
更新
这是我的script.js 文件:
var Hero = require('./hero-model');
// This hero-model.js file defines the schema
// and exports its functionality. I've used
// this model to successfully CRUD data
// via Express. You can ignore the code above
// where I stated require('mongoose') because I was
// merely simplifying. Running this script causes
// the command to terminate silently.
var getHeroes = function() {
Hero.find(function(err, heroes) {
if (err) {
console.log(err);
}
console.log(heroes);
});
};
getHeroes();
【问题讨论】:
-
我也检查过。该应用确实已连接到其数据库。
-
我刚才不是提过,当我使用 Express 时,我可以成功地将文档输出到视图中吗?这意味着我的数据库连接和集合设置得恰到好处。
-
发现问题并解决了。我不得不将我的脚本移动到一个没有安装 Express 作为依赖项的新应用程序中。实际上,Mongoose 是这个新应用的 package.json 文件中定义的唯一依赖项。这很有效。
标签: node.js mongodb express mongoose