Node.js 如何使用Mongojs模块
Mongojs模块是Node.js中的内置模块,用于方便地使用MongoDB与Node.js进行交互。它几乎提供了MongoDB官方API提供的所有功能,并被全球的开发者广泛使用。
按照下面的步骤安装mongojs模块并开始使用它。
项目设置和模块安装:
步骤1: 首先需要在机器上安装npm和node.js。
步骤2: 在所需的项目位置打开命令提示符。您需要创建一个新的NodeJS应用项目(这里命名为gfg)并进行初始化。使用以下命令:
mkdir gfg && cd gfg
npm init -y
步骤3: 使用下面的命令安装mongojs模块:
npm install mongojs
步骤4: 在项目位置创建一个名为“app.js”的文件,您将在其中编写应用程序的核心逻辑。
项目目录: 它将如下所示。
使用Mongojs模块入门: 这里的目标是创建一个简单的应用程序,让您可以将键值对存储在MongoDB数据库中,并根据特定的或所有的条目进行查询。在我们开始之前,请确保您已正确安装了node.js和mongojs,正如之前提到的那样。
我们的思路是在项目中包含mongojs模块,并初始化一个与之相同的数据库连接。然后,我们将使用mongojs模块的’insert()’方法来插入元素,使用’find()’方法来搜索我们集合中的特定元素或所有元素。
您可以参考下面的代码来使用mongojs模块在您的项目中。将下面的代码复制到您在设置项目时创建的app.js文件中。
示例: 在app.js文件中写入下面的代码:
// Include the mongojs module in your project
const mongojs = require("mongojs");
const db = mongojs(
`mongodb+srv://<username>:<password>@cluster0.q2lqx.mongodb.net/
mydb?retryWrites=true&w=majority`,
["mycollection"]
);
// Reports an error if the db cannot
// be initialised properly
db.on("error", function (err) {
console.log("database error", err);
});
// Prints "database connected" in the console
// if the database connection is established
// successfully
db.on("connect", function () {
console.log("database connected");
});
// Insert entries in mongodb database
db.mycollection.insert({ name: "Shruti" });
db.mycollection.insert({ name: "Swati" });
db.mycollection.insert({ name: "Ayushi" });
db.mycollection.insert({ name: "Sanskriti" });
// Query the database for a specific entry
db.mycollection.find({ a: 1 }, function (error, found) {
if (error) {
console.log(error);
} else {
console.log(found);
}
});
// Query the database for all entries
db.mycollection.find({}, function (error, found) {
if (error) {
console.log(error);
} else {
console.log(found);
}
});
运行应用程序的步骤:
使用以下命令运行app.js文件:
node app.js
输出: 你应该在终端屏幕上看到以下输出: