我尝试在另一个进程中执行一些数据库操作,所以我使用了child_process。 但是我无法从这个过程更新我的数据库:没有连接。
app.js
...
mongoose.connect(mongodb://localhost/myDb);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database');
});
// When the connection is disconnected
db.on('disconnected', function () {
console.log('disconnected');
});
child_express.exec('node ' + __dirname + '/path/to/my/my-service.js', (err, stdout, stderr) => {
if(err) console.error(stderr);
else console.log(stdout);
});
我-service.js
MyModel = require('../models/my-model');
...
myModel.updateBook(book);
我-model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// console.log(mongoose.connection.readyState); => 0
var bookSchema = new Schema({..});
var Book = mongoose.model('Book', bookSchema);
exports.updateBook = function(book) {
Book.find({ bookId: book.bookId }, function (err, book) {
console.log(book);
});
};
如何从child_process获取连接?