天蓝色cosmos db在mongodb.com中创建了集合

时间:2020-09-03 12:51:44

标签: mongodb mongoose azure-cosmosdb

当我使用平均堆栈练习一些基本的操作时,我创建了一个名为“ test”的数据库,并在“ videos”集合中,后来我开始学习Cosmos DB,在其中创建了数据库“ cosmos-db-demo”我可以将我的应用程序连接到cosmos DB,但是我很惊讶地看到,当我执行后期操作时,数据被插入到test> collections ...中,而不是cosmos-db-demo>视频收集。该数据库是如何插入的? 记录不应该插入我连接的记录吗?

mongoose.connect('mongodb:// cosmos-db-acc:.... @ cosmos-db-acc.mongo.cosmos.azure.com:10255 /?ssl = true&replicaSet = globaldb&retrywrites = false&maxIdleTimeMS = 120000&appName = @ cosmos-db-acc @')。then(()=> {console.log('已连接到cosmos DB');})。catch((err)=> {console.log(err)}); < / p>

1 个答案:

答案 0 :(得分:1)

关于此问题,我们无法在应用程序中定义数据库名称和连接名称,以告知应用程序连接哪个数据库和连接。关于实现方法,请在连接字符串中添加数据库名称,并在模型中添加{ collection: "<connection name>" }

例如

  1. 创建.env文件
COSMODDB_USER = "<Azure Cosmos account's user name, usually the database account name>"
COSMOSDB_PASSWORD = "<Azure Cosmos account password, this is one of the keys specified in your account>"
COSMOSDB_HOST= "<Azure Cosmos Host name>"
COSMOSDB_PORT=10255
  1. 代码
var mongoose = require("mongoose");
var env = require("dotenv").config();

//connect
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      "User" + //  tell the application to connect which databse
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD,
      },
      useNewUrlParser: true,
      useUnifiedTopology: true,
      retryWrites: false,
    },
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch((err) => console.error(err));

// define model
const Family = mongoose.model(
  "Family",
  new mongoose.Schema(
    {
      lastName: String,
      parents: [
        {
          familyName: String,
          firstName: String,
          gender: String,
        },
      ],
      children: [
        {
          familyName: String,
          firstName: String,
          gender: String,
          grade: Number,
        },
      ],
      pets: [
        {
          givenName: String,
        },
      ],
      address: {
        country: String,
        state: String,
        city: String,
      },
    },
    { collection: "Familay" }, // tell the application to connect which connection
  ),
);

const family = new Family({
  lastName: "Volum",
  parents: [{ firstName: "Thomas" }, { firstName: "Mary Kay" }],
  children: [
    { firstName: "Ryan", gender: "male", grade: 8 },
    { firstName: "Patrick", gender: "male", grade: 7 },
  ],
  pets: [{ givenName: "Buddy" }],
  address: { country: "USA", state: "WA", city: "Seattle" },
});

family.save((err, saveFamily) => {
  console.log(JSON.stringify(saveFamily));
});

enter image description here enter image description here