连接到一个定义的MongoDB

时间:2022-10-04 13:03:40

I have a nodejs application which is connected to a MongoDB, this application has defined its own models and schemas.

我有一个nodejs应用程序,它连接到MongoDB,这个应用程序定义了自己的模型和模式。

For some reason, I need to create another nodejs app which is connected to the same MongoDB the other app is connected to.

由于某种原因,我需要创建另一个nodejs应用,它连接到另一个应用连接到的MongoDB上。

So, do I have to define the same models? Is there a way to extract the models from mongoose?

那么,我需要定义相同的模型吗?有办法从猫鼬身上提取模型吗?

1 个解决方案

#1


3  

You cannot extract models from Mongoose like that, but what you can do is use a MongoDB connection without mongoose, depending on what you need to do. For example:

您不能像这样从Mongoose提取模型,但是您可以做的是使用一个没有MongoDB的连接,这取决于您需要做什么。例如:

Do this in the other app:

在另一个应用中做这个:

MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/db", function(err, db) {
  if(err) { return console.dir(err); }

  var collection = db.collection('users');

    collection.find().toArray(function(err, users) {
        //users comes here.
    });    
});

You have not used the mongoose models here, but you have still connected to the mongodb instance with the native driver.

您在这里没有使用mongoose模型,但是您仍然使用本地驱动程序连接到mongodb实例。

Check this out : https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html

检查一下:https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html

#1


3  

You cannot extract models from Mongoose like that, but what you can do is use a MongoDB connection without mongoose, depending on what you need to do. For example:

您不能像这样从Mongoose提取模型,但是您可以做的是使用一个没有MongoDB的连接,这取决于您需要做什么。例如:

Do this in the other app:

在另一个应用中做这个:

MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/db", function(err, db) {
  if(err) { return console.dir(err); }

  var collection = db.collection('users');

    collection.find().toArray(function(err, users) {
        //users comes here.
    });    
});

You have not used the mongoose models here, but you have still connected to the mongodb instance with the native driver.

您在这里没有使用mongoose模型,但是您仍然使用本地驱动程序连接到mongodb实例。

Check this out : https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html

检查一下:https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html