简体   繁体   English

使用MongoDb和Node.js来组织代码

[英]Organize code using MongoDb with Node.js

I had a Node.js application that do web scraping and save some information in a json object. 我有一个Node.js应用程序,它可以进行网络抓取并将一些信息保存在json对象中。 I have also saved this object to file. 我还将此对象保存到文件中。

Now I want to save these information to a MongoDB database. 现在,我想将这些信息保存到MongoDB数据库中。

This is the structure of my code: 这是我的代码的结构:

app.js file: app.js文件:

var express = require('express');

// my files
var downloaderFirst = require('./routers/downloaderFirst.js');
var downloaderSecond = require('./routers/downloaderSecond.js');

// create app
const app = express();

downloaderFirst.download();
downloaderSecond.download();

./routers/downloaderFirst.js file: ./routers/downloaderFirst.js文件:

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');
var textract = require('textract');

// object of methods
var methods = {};

var url = 'http://www....';

// json object containing data
var jsons = [];

methods.download = function(req, res) {
    extractText();
};

function extractText() {
    // get text and save it to jsons array and ./output/dataFirst.json file
    var thisYear = ...;
    var thisObject = ...;
    var o = {year: thisYear, object: thisObject};
    jsons.push(o);
    printOnFile(jsons, './output/dataFirst.json');
}

module.exports = methods;

./routers/downloaderSecondt.js file: ./routers/downloaderSecondt.js文件:

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');
var textract = require('textract');

// object of methods
var methods = {};

var url = 'http://www....';

// json object containing data
var jsons = [];

methods.download = function(req, res) {
    extractText();
};

function extractText() {
    // get text and save it to jsons array and ./output/dataSecond.json file
    var thisYear = ...;
    var thisColor = ...;
    var o = {year: thisYear, color: thisColor};
    jsons.push(o);
    printOnFile(jsons, './output/dataFirst.json');
}

module.exports = methods;

So now I have two files ( dataFirst.json and dataSecond.json ) containing an object like: 所以现在我有两个文件( dataFirst.jsondataSecond.json ),其中包含一个对象:

dataFirst.json file: dataFirst.json文件:

[{
    "year": "2006",
    "object": "car"
},
{
    "year": "2002",
    "object": "car"
},
{
    "year": "2006",
    "object": "pen"
}, ...];

dataSecond.json file: dataSecond.json文件:

[{
    "year": "2006",
    "color": "red"
},
{
    "year": "2002",
    "color": "blue"
},
{
    "year": "2006",
    "color": "yellow"
}, ...];

I want to save these information to MongoDB using two different collection called first and second . 我想使用两个分别称为firstsecond不同集合将这些信息保存到MongoDB中。 I think I can do two things: 我想我可以做两件事:

  1. get these documents from files and save them all togheter 从文件中获取这些文档并将其全部保存
  2. save a document at time. 一次保存文档。 So, instead of create dataFirst.json and dataSecond.json , save the documnt directly to the right collection of the database. 因此,代替创建dataFirst.jsondataSecond.json ,将文档直接保存到数据库的正确集合中。

Obviously I installed MongoDb drivers using npm install mongodb --save command. 显然,我使用npm install mongodb --save命令安装了MongoDb驱动程序。

Anyway, I want a function to connect (and create if not exists) to db, and insert documents. 无论如何,我想要一个函数来连接(并创建,如果不存在)到db,并插入文档。

So I create ./data/db.js file: 所以我创建了./data/db.js文件:

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/';

// object of methods
var methods = {};

methods.createDb = function(dbName) {
    MongoClient.connect(url + dbName, function(err, db) {
        if(err) {
            throw err;
        }
        console.log('Database created!');
        db.close();
    });
}

methods.createCollection = function(dbName, collectionName) {
    MongoClient.connect(url, function(err, db) {
        if(err) {
            throw err;
        }
        var dbo = db.db(dbName);
        dbo.createCollection(collectionName, function(err, res) {
            if(err) {
                throw err;
            }
            console.log('Collection', collectionName, 'created!');
            db.close();
        });
    });
}

methods.insertDoc = function(dbName, collectionName, doc) {
    MongoClient.connect(url, function(err, db) {
        if(err) {
            throw err;
        }
        var dbo = db.db(dbName);
        dbo.collection(collectionName).insertOne(doc, function(err, res) {
            if(err) {
                throw err;
            }
            console.log('1 document inserted');
            db.close();
        });
    });
}

methods.insertManyDoc = function(dbName, collectionName, docs) {
    MongoClient.connect(url, function(err, db) {
        if(err) {
            throw err;
        }
        var dbo = db.db(dbName);
        dbo.collection(collectionName).insertMany(docs, function(err, res) {
            if(err) {
                throw err;
            }
            console.log('Number of documents inserted: ' + res.insertedCount);
            db.close();
        });
    });
}

methods.insertFromFile = function(dbName, collectionName, filename) {
    var objs = JSON.parse(fs.readFileSync(filename, 'utf8'));
    this.insertManyDoc(dbName, collectionName, objs);
}

module.exports = methods;

For solution (1), I modify my app.js file: 对于解决方案(1),我修改了我的app.js文件:

var express = require('express');

// my files
var downloaderFirst = require('./routers/downloaderFirst.js');
var downloaderSecond = require('./routers/downloaderSecond.js');

var db = require('./data/db.js');
var MongoClient = require('mongodb').MongoClient;

// create app
const app = express();

downloaderFirst.download();
downloaderSecond.download();

var dbName = 'db';
var firstCollectionName = 'first';
var secondCollectionName = 'second';

// create database
db.createDb(dbName);
// create the collections (tables in SQL)
db.createCollection(dbName, firstCollectionName);
db.createCollection(dbName, secondCollectionName);

db.insertFromFile(dbName, firstCollectionName, './output/dataFirst.json');
db.findAll(dbName, firstCollectionName);

The problem is that if I run the project two times, then the collection has doplicate documents, because the insert function doesn't test if the element exists yet or not. 问题是,如果我运行该项目两次,则该集合中有重复的文档,因为insert函数不会测试元素是否存在。

For solution (2) I modify app.js and ./routers/downloaderFirst.js . 对于解决方案(2),我修改了app.js./routers/downloaderFirst.js

app.js file: app.js文件:

var express = require('express');

// my files
var downloaderFirst = require('./routers/downloaderFirst.js');
var downloaderSecond = require('./routers/downloaderSecond.js');

var db = require('./data/db.js');
var MongoClient = require('mongodb').MongoClient;

// create app
const app = express();

downloaderFirst.download();
downloaderSecond.download();

var dbName = 'db';
var firstCollectionName = 'first';
var secondCollectionName = 'second';

// create database
db.createDb(dbName);
// create the collections (tables in SQL)
db.createCollection(dbName, firstCollectionName);
db.createCollection(dbName, secondCollectionName);

./routers/downloaderFirst.js file: ./routers/downloaderFirst.js文件:

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');
var textract = require('textract');
var db = require('../data/db.js');

// object of methods
var methods = {};

var url = 'http://www....';

// json object containing data
var jsons = [];

methods.download = function(req, res) {
    extractText();
};

function extractText() {
    // get text and save it to jsons array and ./output/dataFirst.json file
    var thisYear = ...;
    var thisObject = ...;
    var o = {year: thisYear, object: thisObject};
    jsons.push(o);
    printOnFile(jsons, './output/dataFirst.json');
    db.insertDoc('db', 'first', obj);
}

module.exports = methods;

In this case, I have the same problem (duplicate documents) and then I get this error: 在这种情况下,我有相同的问题(重复的文档),然后出现此错误:

Database created! 数据库已创建! Collection first created! 收藏集首次创建! Collection second created! 收藏集第二个创建! Number of documents inserted: 10692 插入的文档数:10692

C:...\\node_modules\\mongodb\\lib\\mongo_client.js:792 throw err; C:... \\ node_modules \\ mongodb \\ lib \\ mongo_client.js:792抛出错误; ^ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNe tworkError: connect ECONNREFUSED 127.0.0.1:27017] at Pool. ^ MongoNetworkError:首次在Pool上连接[MongoNe tworkError:connect ECONNREFUSED 127.0.0.1:27017]时,无法连接到服务器[localhost:27017]。 (C:...\\node_modules\\mongodb-core \\lib\\topologies\\server.js:503:11) at emitOne (events.js:116:13) at Pool.emit (events.js:211:7) at Connection. (C:... \\ node_modules \\ mongodb-core \\ lib \\ topologies \\ server.js:503:11)位于Pool.emit(events.js:211:7)的emitOne(events.js:116:13)连接。 (C:...\\node_modules\\mongod b-core\\lib\\connection\\pool.js:326:12) at Object.onceWrapper (events.js:317:30) at emitTwo (events.js:126:13) at Connection.emit (events.js:214:7) at Socket. (C:... \\ node_modules \\ mongod b-core \\ lib \\ connection \\ pool.js:326:12)在atmTwoTwo(events.js:126:13)在Object.onceWrapper(events.js:317:30)在Socket的Connection.emit(events.js:214:7)处。 (C:...\\node_modules\\mongodb-co re\\lib\\connection\\connection.js:245:50) at Object.onceWrapper (events.js:315:30) at emitOne (events.js:116:13) (C:... \\ node_modules \\ mongodb-co re \\ lib \\ connection \\ connection.js:245:50)在emitOne(events.js:116:13)在Object.onceWrapper(events.js:315:30)

Anyway, how can I modify my code so to eliminate the duplication problem? 无论如何,我如何修改我的代码以消除重复问题? Is good to connect and close connection each time? 每次连接好并关闭连接好吗? How can I improve my code? 如何改善我的代码? I mean organize better the code. 我的意思是组织更好的代码。

I read a lot of tutorial but I can't solve my problems. 我阅读了很多教程,但无法解决自己的问题。 Sorry, if it is a stupid thing but it's the first time I use Node.js, MongoDb and it's also the first time I do web scraping, so now I'm very confused. 抱歉,如果这很愚蠢,但这是我第一次使用Node.js,MongoDb,也是我第一次进行Web抓取,所以现在我非常困惑。

Thanks! 谢谢!


EDIT 1 编辑1

I modify the code in this way: 我以这种方式修改代码:

app.js : app.js

var express = require('express');

// my files
var downloaderFirst = require('./routers/downloaderFirst.js');
var downloaderSecond = require('./routers/downloaderSecond.js');

var db = require('./data/db.js');
var MongoClient = require('mongodb').MongoClient;

// create app
const app = express();

var dbName = 'db';

// create database
db.createDb(dbName);

downloaderFirst.download();
downloaderSecond.download();

db.disconnectDb(dbName);

./routers/downloaderFirst.js file: ./routers/downloaderFirst.js文件:

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');
var textract = require('textract');
var db = require('../data/db.js');

// object of methods
var methods = {};

var url = 'http://www....';

// json object containing data
var jsons = [];

methods.download = function(req, res) {
    extractText();
};

function extractText() {
    // get text and save it to jsons array and ./output/dataFirst.json file
    var thisYear = ...;
    var thisObject = ...;
    var o = {year: thisYear, object: thisObject};
    jsons.push(o);
    printOnFile(jsons, './output/dataFirst.json');
    db.insertDocFirst('db', 'first', obj);
}

module.exports = methods;

Where db.js is: db.js在哪里:

var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/';

// object of methods
var methods = {};

methods.createDb = function(dbName) {
    MongoClient.connect(url + dbName, function(err, db) {
        if(err) {
            console.log('createDb', err);
            //throw err;
        }
        console.log('Database created!');
        var dbo = db.db(dbName);
        var first = dbo.createCollection('first', function(err, res) {
            if(err) {
                console.log('create collection first', err);
                //throw err;
            }
            console.log('Collection first created!');
            /*// because we are searching by name, we need an index! without an index, things can get slow
            first.ensureIndex({year: true, object: true}, function(err) {
                if(err) {
                    throw err;
                }
            });
            console.log('Index of collection first created!');*/
        });
        var second = dbo.createCollection('second', function(err, res) {
            if(err) {
                console.log('create collection second', err);
                //throw err;
            }
            console.log('Collection second created!');
            /*// because we are searching by name, we need an index! without an index, things can get slow
            dbo.collection('second').createIndex({year: true, color: true}, function(err) {
                if(err) {
                    console.log('ensureIndex second', err);
                    //throw err;
                }
            });
            console.log('Index of collection second created!');*/
        });
    });
}

methods.disconnectDb = function(dbName) {
    MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log('disconnectDb', err)
            //throw err;
        }
        console.log('Disconnected. Bye :)');
        db.close();
    });
}

methods.insertDocFirst = function(dbName, collectionName, doc) {
    MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log('insertDoc', err); // ** ERROR HERE **
            //throw err;
        }
        var dbo = db.db(dbName);
        var selector = {
            "year": doc.year,
            "color": doc.color
        };
        dbo.collection(collectionName).update(selector, doc, {upsert: true});
    });
}

methods.insertDocSecond = function(dbName, collectionName, doc) {
    MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log('insertDoc', err);
            //throw err;
        }
        var dbo = db.db(dbName);
        var selector = {
            "year": doc.year,
            "object": doc.color
        };
        dbo.collection(collectionName).update(selector, doc, {upsert: true});
    });
}

When I run the code, I get: 运行代码时,我得到:

Disconnected. Bye :)
Database created!
insertDoc { MongoNetworkError: failed to connect to server [localhost:27017] on first conn
ect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (C:\...\node_modules\mongodb-core
\lib\topologies\server.js:503:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (C:\...\node_modules\mongod
b-core\lib\connection\pool.js:326:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (C:\...\node_modules\mongodb-co
re\lib\connection\connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
  name: 'MongoNetworkError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkEr
ror: connect ECONNREFUSED 127.0.0.1:27017]' }
C:\...\node_modules\mongodb\lib\mongo_client.js:792
          throw err;
          ^

TypeError: Cannot read property 'db' of null
    at C:\...\data\db.js:105:16
    at err (C:\...\node_modules\mongodb\lib\utils.js:414:
14)
    at executeCallback (C:\...\node_modules\mongodb\lib\u
tils.js:403:25)
    at C:\Users\...\node_modules\mongodb\lib\mongo_client.js:27
0:21
    at connectCallback (C:\...\node_modules\mongodb\lib\m
ongo_client.js:940:5)
    at C:\...\node_modules\mongodb\lib\mongo_client.js:78
9:11
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Obviously I before start MongoDb in this way: 显然,我在以这种方式启动MongoDb之前:

mongod -dbpath C:\...\data

What is the problem? 问题是什么?


EDIT 2 编辑2

Thanks a lot for your help. 非常感谢你的帮助。 I'm trying to modify the cose adding the creation of collections. 我正在尝试修改cose以添加集合的创建。

This is now my code. 现在这是我的代码。

app.js : app.js

var express = require('express');

// my files
var downloaderFirst = require('./routers/downloaderFirst.js');
var downloaderSecond = require('./routers/downloaderSecond.js');

var db = require('./data/db.js');

// create app
const app = express();

downloaderFirst.download();
downloaderSecond.download();

db.js : db.js

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
let dbInstance;

// object of methods
var methods = {};

const connectDb = function(dbName, cb) {
    if(dbInstance) {
        return cb(dbInstance);
    }
    else {
        MongoClient.connect(url + dbName, function(err, db) {
            if(!err) {
                dbInstance = db;
                return cb(db);
            }
        });
    }
}

methods.insertFirst = function(dbName, collectionName, doc) {
    connectDb(dbName, function(db) {
        var dbo = db.db(dbName);
        var selector = {
            year: doc.year,
            color: doc.color
        };
        dbo.collection(collectionName).update(selector, doc, {upsert: true});
    });
}

methods.insertSecond = function(dbName, collectionName, doc) {
    connectDb(dbName, function(db) {
        var dbo = db.db(dbName);
        var selector = {
            year: doc.year,
            object: doc.object
        };
        dbo.collection(collectionName).update(selector, doc, {upsert: true});
    });
}

./routers/downloaderFirst.js : ./routers/downloaderFirst.js

var cheerio = require('cheerio');
var express = require('express');
var fs = require('fs');
var request = require('request');
var textract = require('textract');
var db = require('../data/db.js');

// object of methods
var methods = {};

var url = 'http://www....';

// json object containing data
var jsons = [];

methods.download = function(req, res) {
    extractText();
};

function extractText() {
    // get text and save it to jsons array and ./output/dataFirst.json file
    var thisYear = ...;
    var thisObject = ...;
    var o = {year: thisYear, object: thisObject};
    jsons.push(o);
    printOnFile(jsons, './output/dataFirst.json');
    db.insertFirst('db', 'first', obj);
}

module.exports = methods;

When I run, I get: 当我跑步时,我得到:

(node:5708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1
): MongoError: BSON field 'update.updates.q' is the wrong type 'array', expected type 'obj
ect'
(node:5708) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the Node.js process wit
h a non-zero exit code.
(node:5708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2
): MongoError: BSON field 'update.updates.q' is the wrong type 'array', expected type 'obj
ect'
(node:5708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3
): MongoError: BSON field 'update.updates.q' is the wrong type 'array', expected type 'obj
ect'
^C

Then I can use Compass to analyse my db. 然后,我可以使用Compass来分析我的数据库。 I see that collections are created, but there aren't all the documents that should be there. 我看到创建了集合,但是并没有所有应该存在的文档。 Should be there 10692 documents in 'second' collection and 16102 documents in 'first' collection but there are 2398 documents in 'second' collection and 933 documents in 'first' collection. “第二”集合中应该有10692个文档,“第一”集合中应该有16102个文档,但是“第二”集合中应该有2398个文档,而“第一”集合中应该有933个文档。

And then, I thought about how (and when) call db.close(). 然后,我考虑了如何(以及何时)调用db.close()。 The problem is that my app should do web scraping, save information on db an visualize data using d3.js. 问题是我的应用程序应该进行网络抓取,将信息保存在db上,并使用d3.js可视化数据。 Now I would like to put db.close() when the app finish to save all the information on db. 现在,我想在应用程序完成时将db.close()保存到db上。

If node was synchronous, I will would made something like that: 如果节点是同步的,我会做类似的事情:

app.js : app.js

var express = require('express');

// my files
var downloaderFirst = require('./routers/downloaderFirst.js');
var downloaderSecond = require('./routers/downloaderSecond.js');

var db = require('./data/db.js');

// create app
const app = express();

// web scraping and saving on db
downloaderFirst.download();
downloaderSecond.download();

// close connection
db.disconnectDb();

where disconnectDb() is in db.js : db.js中的offlineDb ()所在的位置

methods.disconnectDb = function(dbName) {
    connectDb(dbName, function(db) {
        var dbo = db.db(dbName);
        db.close();
    });
}

But this couldn't work. 但这行不通。 So, any tips? 那么,有什么建议吗? It's the very first time I use Node and Mongo, I read a lot but I can't find complete (and not very very simple) examples that shows how to build an app different from "Hello World!". 这是我第一次使用Node和Mongo,我读了很多书,但找不到完整的(也不是非常简单的)示例来说明如何构建与“ Hello World!”不同的应用程序。

Thanks 谢谢

NodeJs has asynchronous nature. NodeJ具有异步特性。 It has single thread event-driven Architecture setup. 它具有单线程事件驱动的体系结构设置。 So, when you are connecting and disconnecting a database connection at each function call, may be some other resource or function is trying to do the same operation. 因此,在每个函数调用中连接和断开数据库连接时,可能是某些其他资源或函数正在尝试执行相同的操作。

Example - function A has created a mongodb connection and there is some other function which is also trying to do the same. 示例 - function A创建了mongodb连接,还有其他一些函数也在尝试这样做。 So this error occurs like what ever you are facing. 因此,发生此错误的方式与您面临的情况相同。

Solution - Maintain a file where you connect database at the time of app start. 解决方案 -在启动应用程序时维护一个文件,用于在其中连接数据库。 when your complete application is going to stop or you are sure about the termination of your application then just disconnect the database connection. 当完整的应用程序将要停止或您确定应用程序将终止时,只需断开数据库连接即可。 This way there will be no race-around conditions on open and close . 这样, openclose就不会出现race-around条件。

EDITED - 1 编辑-1

I am adding few more lines based on your edited code. 我将根据您编辑的代码再添加几行。

  1. The app.js file has following lines app.js文件具有以下几行

     1. db.createDb(dbName); //this is an asynchronous operation 2. downloaderFirst.download(); //this is a route (asynchronous) as per your code base 3. downloaderSecond.download(); //this is a route (asynchronous) as per your code base 4. db.disconnectDb(dbName); // this is an asynchronous operation too 

Now line no. 现在行号 4 is not going to wait to execute for line number 1,2,3 because of Nodejs event-driven architecture. 由于Nodejs事件驱动的体系结构,第4行不会等待执行第1,2,3行。 So when you run this code MongoDB is connected and disconnected at the same time independently of each other based on event-loop . 因此,当您运行此代码时,基于event-loop MongoDB会彼此独立地同时connecteddisconnected

  1. The downloaderFirst.js has this function downloaderFirst.js具有此功能

     function extractText() { var thisYear = ...; var thisObject = ...; var o = {year: thisYear, object: thisObject}; jsons.push(o); printOnFile(jsons, './output/dataFirst.json'); db.insertDocFirst('db', 'first', obj); /*********HERE*****/ } 

    Please see the HERE marked line. 请在HERE查看标记的行。 This one is again asynchronous and does not wait for MongoDb connect . 这又是异步的,不等待MongoDb连接。 If the extractText function is called it starts to execute. 如果调用extractText函数,它将开始执行。

  2. The db.js file has few problems. db.js文件几乎没有问题。

Here you are connecting the database on each operation, which has downsides of multiple connection request at the same time. 在这里,您要在每个操作上连接数据库,这同时具有多个连接请求的缺点。 So it can be done like this way. 因此,可以通过这种方式完成。

Create one function called connectDb . 创建一个名为connectDb函数。 which returns the connected db instance.Then use it for other database operations like this way. 它将返回连接的db实例。然后将其用于其他数据库操作,例如这种方式。

let dbInstance;
const connectDb = function(dbName,cb){
    if(dbInstance){
         return cb(dbInstance);
    }else{
        MongoClient.connect(url + dbName,function(err,db){
              if(!err){
                 dbInstance = db;
                 return cb(db);
              }
        })

    }
 } 

So use this function to connect MongoDB . 因此,使用此功能连接MongoDB And write other operations like this. 并编写其他类似的操作。

methods.insertDocSecond = function(dbName, collectionName, doc) {
    connectDb(dbName,function(db){
        var dbo = db.db(dbName);
        var selector = {
            "year": doc.year,
            "object": doc.color
        };
        dbo.collection(collectionName).update(selector, doc, {upsert: true}); 
    })
}

This way we can ensure that database is connected one time only and rest of the times its passing the reference only. 这样,我们可以确保数据库仅连接一次,其余时间仅通过引用进行连接。

And last but not the least please make sure to call close connection in a proper way so it does not get called asynchronously when some other function is busy in doing some database operation. 最后但并非最不重要的一点是,请确保以适当的方式调用close连接,以便在某些其他函数忙于执行某些数据库操作时不会异步调用该连接。

EDITED-2 EDITED-2

Update function returns promise and callback both. Update函数同时返回promise和callback。 For your current scenario, your update operation is returning some error which is not handled. 对于您当前的情况,您的update操作将返回一些未处理的错误。 Use callback function to grab the error properly and see where it is breaking. 使用回调函数正确捕获错误并查看错误所在。

Anyways I found you have some understanding issue on how to work with Nodejs and MongoDB , rather than you are stuck into a problem which is StackOverflow is for.So I must advise you to go through some online material, resources to find out how to work with Nodejs and MongoDB together and then if you are stuck into any particular problem, the community will be happy to help you. 无论如何,我发现您对如何使用NodejsMongoDB有一些了解的问题,而不是陷入StackOverflow所针对的问题,因此我必须建议您仔细阅读一些在线资料和资源以了解如何工作与Nodejs和MongoDB一起使用,然后如果您遇到任何特定问题,社区将很乐意为您提供帮助。 Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM