在没有Express的情况下,如何通过Mongoose与MongoDB进行交互? [英] How can I interact with MongoDB via Mongoose without Express?

查看:41
本文介绍了在没有Express的情况下,如何通过Mongoose与MongoDB进行交互?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可以使我对CRUD操作如何工作有扎实了解的环境.到目前为止,我一直在使用views来查看数据的外观,但是具有明显的灵活性,这种方法不是很有见地的-就像在黑暗中行驶.

I'd like an environment where I can get a solid grasp of how CRUD operations work. Up to this point, I've been using views to see how the data looks like but with the obvious inflexibility, this approach isn't that insightful -- it's something like driving in the dark.

现在,我希望能够通过Mongoose提供的功能来处理MongoDB中的数据,以便我了解执行此操作或子文档,填充等工作时实际发生的情况.最初,我将此代码保存在script.js文件中:

Now I want to be able to work with the data in MongoDB via the functionality offered by Mongoose so that I see what actually happens when I do this or that, subdocuments, population, that sort of stuff. Initially, I had this code in a script.js file:

var mongoose = require('mongoose');
// ...
// define schemas
// try some crazy things
// ...
console.log(results);

然后我尝试执行该代码:

And then I attempted to execute that code:

node script.js

哪个没用.然后,我尝试了:

Which didn't work. I then tried:

mongo load('script.js')

这一次,我当然出错了-没有定义require(). Facepalm.

This time, I got an error, of course -- require() is not defined. Facepalm.

希望这会让您对我正在尝试做的事情有个了解.此后,我尝试了其他似乎无效的方法.

Hopefully that gives you an idea of what I'm trying to do. I've since tried other methods that didn't seem to work.

请告知.

更新

这是我的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();

推荐答案

您正在尝试将节点脚本作为mongo shell脚本运行.要将其作为常规节点脚本运行,只需使用:

You're trying to run a node script as a mongo shell script. To run it as a regular node script, simply use:

node script.js

这篇关于在没有Express的情况下,如何通过Mongoose与MongoDB进行交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆