【问题标题】:Mongoose connection to a MongoDBMongoose 与 MongoDB 的连接
【发布时间】:2020-11-02 08:19:21
【问题描述】:

我正在尝试使用 Angular 8 中的 mongoose.createConnection 连接到 mongodb,但我一直遇到此错误:

mongoose.createConnection is not a function

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { RouteSegments } from '../mm-routing.module';

@Component({
  selector: 'elastic-search',
  templateUrl: './elastic-search.component.html',
  styleUrls: ['./elastic-search.component.scss']
})
export class ElasticSearchComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

    open() {
      debugger;
      const mongoose = require('mongoose');

      const connection = mongoose.createConnection('mongodb://Test/Test', { useNewUrlParser: true });

      var bookSchema = new mongoose.Schema({
        title: String,
        author: String,
        description: String
      });

      var Book = mongoose.model("Book", bookSchema);

    }
}

我也尝试过使用 mongoose.connection,但我在控制台中遇到了同样的错误。

【问题讨论】:

  • 你能告诉我们控制台输出什么错误。
  • mongoose.createConnection 不是一个函数,总是这个。
  • @RobNone,根据mongoose code examplecreateConnection 的调用似乎是正确的。尽管您设法摆脱了 console 错误,但我们无法直接从 Angular 代码或任何客户端代码直接连接到 mongodb

标签: angular mongodb typescript mongoose frontend


【解决方案1】:

我们无法从客户端代码(Angular/React 等)直接连接到 DB。

使用任何服务器端技术,如 NodeExpress.js 或尝试使用 Angular Universal SSR,如 here 所述。

【讨论】:

  • 不幸的是,我总是得到“createConnection 不是函数”。
  • 首先感谢您的帮助。我正在尝试按照本教程更清楚compose.com/articles/…
猜你喜欢
  • 2020-06-07
  • 2019-07-11
  • 2020-05-05
  • 2021-05-12
  • 2013-01-18
  • 2018-11-05
  • 2019-02-22
  • 1970-01-01
相关资源
最近更新 更多