forked from Giveth/feathers-giveth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoose.js
52 lines (44 loc) · 1.52 KB
/
mongoose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const mongoose = require('mongoose');
require('mongoose-long')(mongoose);
require('./models/mongoose-bn')(mongoose);
const logger = require('winston');
// mongoose query hook function that will
// remove the key from the doc if the value is undefined
function unsetUndefined(next) {
const query = this;
if (['findOneAndUpdate', 'update', 'updateMany'].includes(this.op)) {
this._update = this._update || {};
Object.keys(this._update).forEach(k => {
if (query._update[k] === undefined) {
delete query._update[k];
if (!query._update.$unset) query._update.$unset = {};
query._update.$unset[k] = true;
}
});
} else {
logger.warn('mongoose hook ignoring unhandled `op`:', this.op, '\n', this);
}
next();
}
module.exports = function mongooseFactory() {
const app = this;
const mongoUrl = app.get('mongodb');
logger.info('Using feathers mongo url', mongoUrl);
mongoose.connect(mongoUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
const db = mongoose.connection;
db.on('error', err => logger.error('Could not connect to Mongo', err));
db.once('open', () => logger.info('Connected to Mongo'));
mongoose.plugin(schema => {
// feathers-mongoose only uses the following 2 calls
schema.pre('update', unsetUndefined);
schema.pre('updateMany', unsetUndefined);
schema.pre('findOneAndUpdate', unsetUndefined);
});
mongoose.Promise = global.Promise;
app.set('mongooseClient', mongoose);
};