- Notifications
You must be signed in to change notification settings - Fork41
A mongodb service for feathers
License
feathersjs-ecosystem/feathers-mongodb
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Important: This module has been moved to
@feathersjs/mongodband is developed infeathersjs/feathers
AFeathers database adapter forMongoDB usingofficial NodeJS driver for MongoDB.
$ npm install --save mongodb feathers-mongodb
Important:
feathers-mongodbimplements theFeathers Common database adapter API andquerying syntax.
This adapter also requires arunning MongoDB database server.
Returns a new service instance initialized with the given options.Model has to be a MongoDB collection.
constMongoClient=require('mongodb').MongoClient;constservice=require('feathers-mongodb');MongoClient.connect('mongodb://localhost:27017/feathers').then(client=>{app.use('/messages',service({Model:client.db('feathers').collection('messages')}));app.use('/messages',service({ Model, id, events, paginate}));});
Options:
Model(required) - The MongoDB collection instanceid(optional, default:'_id') - The name of the id field property. By design, MongoDB will always add an_idproperty.disableObjectify(optional, defaultfalse) - This will disable the objectify of the id field if you want to use normal stringsevents(optional) - A list ofcustom service events sent by this servicepaginate(optional) - Apagination object containing adefaultandmaxpage sizewhitelist(optional) - A list of additional query parameters to allow (e..g[ '$regex', '$geoNear' ])multi(optional) - Allowcreatewith arrays andupdateandremovewithidnullto change multiple items. Can betruefor all methods or an array of allowed methods (e.g.[ 'remove', 'create' ])useEstimatedDocumentCount(optional, defaultfalse) - Iftruedocument counting will rely onestimatedDocumentCountinstead ofcountDocuments
When making aservice method call,params can contain anmongodb property (for example,{upsert: true}) which allows to modify the options used to run the MongoDB query.
You can utilized aMongoDB Transactions by passing asession with theparams.mongodb:
import{ObjectID}from'mongodb'exportdefaultasyncapp=>{app.use('/fooBarService',{asynccreate(data){// assumes you have access to the mongoClient via your app stateletsession=app.mongoClient.startSession()try{awaitsession.withTransaction(async()=>{letfooID=newObjectID()letbarID=newObjectID()app.service('fooService').create({ ...data,_id:fooID,bar:barID,},{mongodb:{ session}},)app.service('barService').create({ ...data,_id:barIDfoo:fooID},{mongodb:{ session}},)})}finally{awaitsession.endSession()}}})}
Here is an example of a Feathers server with amessages endpoint that writes to thefeathers database and themessages collection.
$ npm install @feathersjs/feathers @feathersjs/errors @feathersjs/express @feathersjs/socketio feathers-mongodb mongodbInapp.js:
constfeathers=require('@feathersjs/feathers');constexpress=require('@feathersjs/express');constsocketio=require('@feathersjs/socketio');constMongoClient=require('mongodb').MongoClient;constservice=require('feathers-mongodb');// Create an Express compatible Feathers application instance.constapp=express(feathers());// Turn on JSON parser for REST servicesapp.use(express.json());// Turn on URL-encoded parser for REST servicesapp.use(express.urlencoded({extended:true}));// Enable REST servicesapp.configure(express.rest());// Enable Socket.ioapp.configure(socketio());// Connect to the db, create and register a Feathers service.app.use('/messages',service({paginate:{default:2,max:4}}));// A basic error handler, just like Expressapp.use(express.errorHandler());// Connect to your MongoDB instance(s)MongoClient.connect('mongodb://localhost:27017/feathers').then(function(client){// Set the model now that we are connectedapp.service('messages').Model=client.db('feathers').collection('messages');// Now that we are connected, create a dummy Messageapp.service('messages').create({text:'Message created on server'}).then(message=>console.log('Created message',message));}).catch(error=>console.error(error));// Start the server.constport=3030;app.listen(port,()=>{console.log(`Feathers server listening on port${port}`);});
Run the example withnode app and go tolocalhost:3030/messages.
Additionally to thecommon querying mechanism this adapter also supportsMongoDB's query syntax and theupdate method also supports MongoDBupdate operators.
Important: External query values through HTTP URLs may have to be converted to the same type stored in MongoDB in a beforehook otherwise no matches will be found. Websocket requests will maintain the correct format if it is supported by JSON (ObjectIDs and dates still have to be converted).
For example, anage (which is a number) a hook like this can be used:
constObjectID=require('mongodb').ObjectID;app.service('users').hooks({before:{find(context){const{ query={}}=context.params;if(query.age!==undefined){query.age=parseInt(query.age,10);}context.params.query=query;returnPromise.resolve(context);}}});
Which will allows queries like/users?_id=507f1f77bcf86cd799439011&age=25.
This adapter includes support forcollation and case insensitive indexes available in MongoDB v3.4. Collation parameters may be passed using the specialcollation parameter to thefind(),remove() andpatch() methods.
The example below would patch all student records with grades of'c' or'C' and above (a natural language ordering). Without collations this would not be as simple, since the comparison{ $gt: 'c' } would not include uppercase grades of'C' because the code point of'C' is less than that of'c'.
constpatch={shouldStudyMore:true};constquery={grade:{$gte:'c'}};constcollation={locale:'en',strength:1};students.patch(null,patch,{ query, collation}).then( ...);
Similar to the above example, this would find students with a grade of'c' or greater, in a case-insensitive manner.
constquery={grade:{$gte:'c'}};constcollation={locale:'en',strength:1};students.find({ query, collation}).then( ...);
For more information on MongoDB's collation feature, visit thecollation reference page.
Copyright (c) 2019
Licensed under theMIT license.
About
A mongodb service for feathers
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.