私はmongodbでnode-mongodb-nativeドライバを使用してWebサイトを作成しています。node.jsでmongodb接続を再利用する方法
、その後のデータを保存/挿入するために、私は一度MongoDBの接続をオープンする方法についての質問があり、その後、comment.js
にuser.js
でコレクション名のユーザーにそれを使用すると、コレクション名のポスト私はdb.js
でDB接続を開きたいですユーザーとポスト収集
現在のコードは、私のdb.js
var Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server;
module.exports = new Db(
'blog',
new Server('localhost', Connection.DEFAULT_PORT, {auto_reconnect: true})
);
私は
user.js
で
db.js
を使用
var mongodb = require('mongodb');
var events = require('events');
var event = new events.EventEmitter();
var access = new mongodb.Server(host, port, { });
var client = null;
new mongodb.Db('YOUR DATABASE', access, { safe: true, auto_reconnect: true }).open(function (err, c) {
if (!err) {
client = c;
console.log('database connected');
event.emit('connect');
} else {
console.log('database connection error', err);
event.emit('error');
}
});
exports.get = function(fn) {
if(client) {
fn(client);
} else {
event.on('connect', function() {
fn(client);
});
}
};
し、それを再利用:sがあなたが一度接続し、あなたは何度でもそれを再利用することができ
var mongodb = require('./db');
function User(user){
this.name = user.name;
this.password = user.password;
this.email = user.email;
};
module.exports = User;
User.prototype.save = function(callback) {//save user information
//document to save in db
var user = {
name: this.name,
password: this.password,
email: this.email
};
mongodb.close();
//open mongodb database
mongodb.open(function(err, db){
if(err){
return callback(err);
}
//read users collection
db.collection('users', function(err, collection){
if(err){
mongodb.close();
return callback(err);
}
//insert data into users collections
collection.insert(user,{safe: true}, function(err, user){
mongodb.close();
callback(err, user);//success return inserted user information
});
});
});
};
とcomment.js
var mongodb = require('./db');
function Comment(name, day, title, comment) {
this.name = name;
this.day = day;
this.title = title;
this.comment = comment;
}
module.exports = Comment;
Comment.prototype.save = function(callback) {
var name = this.name,
day = this.day,
title = this.title,
comment = this.comment;
mongodb.open(function (err, db) {
if (err) {
return callback(err);
}
db.collection('posts', function (err, collection) {
if (err) {
mongodb.close();
return callback(err);
}
//depend on name time and title add comment
collection.findAndModify({"name":name,"time.day":day,"title":title}
, [ ['time',-1] ]
, {$push:{"comments":comment}}
, {new: true}
, function (err,comment) {
mongodb.close();
callback(null);
});
});
});
};
あなたの質問は質問のようには聞こえません。何が起こっていない、あなたが直面している正確な挑戦を投稿してください。 – moka