郝 玉华

郝 玉华

1661407860

在 Next.Js 应用程序中连接多个 MongoDB 数据库

我们知道 Next.js 是框架比 React.js 库要好得多。作为一个全栈框架,Next.js 可以同时处理前端和后端。我们可以创建 API 路由并将数据库连接到我们的应用程序。在这里,我们将讨论在 Next.js 应用程序中连接多个 MongoDB 数据库的方法。

先决条件

这篇文章被认为是我之前关于将 MongoDB 数据库与 Next.js 应用程序连接起来的文章的延续。您必须参考它以获得更好的理解。文章的网址如下所示。

如何将 MongoDB Atlas 与 Next.js 应用程序连接起来

我们将学到什么

参考我之前的文章后,您将对连接 MongoDB Atlas 和 Next.js 应用程序有更好的理解。

除此之外,完成本文将使您了解在单个 Next.js 应用程序中连接多个数据库。

  • 我们将在 MongoDB Atlas 中创建两个数据库
  • 在 Next.js 应用程序中列出每个数据库中的数据。

完成本文后,我们将创建一篇文章,显示来自两个数据库的用户列表。如下所示。

在 MongoDB Atlas 中创建两个数据库

我们用截图转换了上一篇文章中创建数据库和集合的所有步骤。参考它并在MongoDB Atlas中创建两个数据库。

在这里,我给出了在 MongoDB Atlas 中创建的两个数据库的屏幕截图。

数据库名称是nextjs-mongodb-atlas-demonextjs-api-demo。这两个数据库包含带有一些虚拟数据的集合用户。

我们将在 Next.js 应用程序中连接这两个数据库并显示两个用户列表。

创建一个新的 Next.js 项目

在我们的系统上成功安装 Node.js后,我们可以使用以下命令创建一个新的 Next.js 项目。创建项目后,进入项目目录,用VS代码打开。

npx create-next-app nextjs-multiple-mongodb-databases

cd nextjs-multiple-mongodb-databases

code.

设置本地环境变量

创建数据库和集合后,我们将从 MongoDB Atlas 获取连接字符串。您需要参考上一篇文章以获取更多详细信息。

现在,添加从 MongoDB Atlas 复制的连接字符串。它应该类似于下面的那个。

MONGODB_URI= "mongodb+srv://techomoro123:qk7ap0dFcwvYdo12@cluster0.7cpxz.mongodb.net?retryWrites=true&w=majority"

这里,  techomoro123 是用户名,  qk7ap0dFcwvYdo12 是密码。你必须用你的替换它。

在我们的项目中创建一个名为 .env.local的文件 并将内容复制到其中。

MONGODB_URI= "mongodb+srv://techomoro123:qk7ap0dFcwvYdo12@cluster0.7cpxz.mongodb.net?retryWrites=true&w=majority"

请注意,我们没有在此处指定数据库名称。因为我们稍后会连接数据库。

安装 MongoDB

我们需要安装 MongoDB 包 才能在 Next.js 应用程序中使用 MongoDB。我认为 3.5.9 版本更兼容。所以我们可以安装它。

npm i mongodb@3.5.9

设置 MongoDB 连接

 在 lib 目录中创建一个名为 mongodb.js的文件。并添加以下代码以创建从 Next.js 应用程序到 MongoDB 的连接。

请注意,我们在这里也没有指定数据库名称。因为我们稍后会这样做。

// lib/mongodb.js

import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.MONGODB_URI) {
  throw new Error('Please add your Mongo URI to .env.local')
}

if (process.env.NODE_ENV === 'development') {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

创建一个 API 路由以从数据库 1 中获取用户列表

我们需要创建两个 API 路由来从数据库 1 和数据库 2 中获取用户列表。

选择数据库由以下代码完成。

const db1 = client.db("nextjs-api-demo");

因此,在pages/api/users目录中,创建一个名为one.js的文件并连接数据库 1并获取用户列表。

// pages/api/users/one.js

import clientPromise from "../../../lib/mongodb";

export default async function handler(req, res) {
  const client = await clientPromise;

  const db1 = client.db("nextjs-api-demo");
  switch (req.method) {
    case "GET":
      const users1 = await db1.collection("users").find({}).toArray();
      res.json(users1);
      break;
  }
}

创建 API 路由以从数据库 2 中获取用户列表

以上面讨论的相同方式,创建一个two.js文件来连接数据库 2并列出所有用户。

这里也使用以下代码选择数据库。

const db2 = client.db("nextjs-mongodb-atlas-demo");

这样整个two.js文件将如下所示。

// pages/api/users/two.js

import clientPromise from "../../../lib/mongodb";

export default async function handler(req, res) {
  const client = await clientPromise;

  const db2 = client.db("nextjs-mongodb-atlas-demo");
  switch (req.method) {
    case "GET":
      const users2 = await db2.collection("users").find({}).toArray();
      res.json(users2);
      break;
  }
}

在 getStaticProps 中调用 API 路由

这样我们的两个 API 端点就准备好了,我们可以调用这些 API 来从数据库 1 和数据库 2 中获取用户列表。

我在getServerSideProps生命周期方法中调用 API 请求。我们还可以从getServerSideProps甚至从useEffect函数内部调用这些 API。

export async function getStaticProps(context) {
  let res1 = await fetch("http://localhost:3000/api/users/one", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });
  let users1 = await res1.json();

  let res2 = await fetch("http://localhost:3000/api/users/two", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });
  let users2 = await res2.json();

  return {
    props: { users1, users2 },
  };
}

现在可以在我们的应用程序中显示此用户列表。这样整个index.js文件将如下所示。

// 页面/index.js

export default function Home({ users1, users2 }) {
  return (
    <div className="container">
      <div className="left">
        <h1>Users 1 from DB 1</h1>
        {users1.map((user, index) => {
          return (
            <div className="card" key={index}>
              <h2>{user.name}</h2>
              <p>{user.email}</p>
              <p>{user.mobile}</p>
            </div>
          );
        })}
      </div>

      <div className="right">
        <h1>Users 2 from DB 2</h1>
        {users2.map((user, index) => {
          return (
            <div className="card" key={index}>
              <h2>{user.name}</h2>
              <p>{user.email}</p>
              <p>{user.mobile}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export async function getStaticProps(context) {
  let res1 = await fetch("http://localhost:3000/api/users/one", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });
  let users1 = await res1.json();

  let res2 = await fetch("http://localhost:3000/api/users/two", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });
  let users2 = await res2.json();

  return {
    props: { users1, users2 },
  };
}

代码沙盒

请参阅 CodeSandbox 链接以查看实时应用程序。您可以将此项目克隆到您的 CodeSandbox 帐户并编辑代码。

https://codesandbox.io/s/sharp-grass-94n8o

GitHub

你总是可以参考 GitHub 存储库来克隆这个项目,参考代码并在它之上工作。

https://github.com/techomoro/nextjs-multiple-mongodb-databases

概括

在这里,我们讨论了在 Next.js 应用程序中连接多个 MongoDB 数据库的步骤。

来源:https ://www.techomoro.com/connect-multiple-mongodb-databases-in-a-next-js-app/

#mongodb #database #nextjs 

What is GEEK

Buddha Community

在 Next.Js 应用程序中连接多个 MongoDB 数据库

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Eva  Murphy

Eva Murphy

1625674200

Google analytics Setup with Next JS, React JS using Router Events - 14

In this video, we are going to implement Google Analytics to our Next JS application. Tracking page views of an application is very important.

Google analytics will allow us to track analytics information.

Frontend: https://github.com/amitavroy/video-reviews
API: https://github.com/amitavdevzone/video-review-api
App link: https://video-reviews.vercel.app

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #js #react js #react #next #google analytics

Query of MongoDB | MongoDB Command | MongoDB | Asp.Net Core Mvc

https://youtu.be/FwUobnB5pv8

#mongodb tutorial #mongodb tutorial for beginners #mongodb database #mongodb with c# #mongodb with asp.net core #mongodb

Install MongoDB Database | MongoDB | Asp.Net Core Mvc

#MongoDB
#Aspdotnetexplorer

https://youtu.be/cnwNWzcw3NM

#mongodb #mongodb database #mongodb with c# #mongodb with asp.net core #mongodb tutorial for beginners #mongodb tutorial

Eva  Murphy

Eva Murphy

1625751960

Laravel API and React Next JS frontend development - 28

In this video, I wanted to touch upon the functionality of adding Chapters inside a Course. The idea was to not think much and start the development and pick up things as they come.

There are places where I get stuck and trying to find answers to it up doing what every developer does - Google and get help. I hope this will help you understand the flow and also how developers debug while doing development.

App url: https://video-reviews.vercel.app
Github code links below:
Next JS App: https://github.com/amitavroy/video-reviews
Laravel API: https://github.com/amitavdevzone/video-review-api

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #api #react next js #next #frontend #development