Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A mongodb service for feathers

License

NotificationsYou must be signed in to change notification settings

feathersjs-ecosystem/feathers-mongodb

Repository files navigation

Important: This module has been moved to@feathersjs/mongodb and is developed infeathersjs/feathers

feathers-mongodb

CIDependency StatusDownload Status

AFeathers database adapter forMongoDB usingofficial NodeJS driver for MongoDB.

$ npm install --save mongodb feathers-mongodb

Important:feathers-mongodb implements theFeathers Common database adapter API andquerying syntax.

This adapter also requires arunning MongoDB database server.

API

service(options)

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 instance
  • id (optional, default:'_id') - The name of the id field property. By design, MongoDB will always add an_id property.
  • disableObjectify (optional, defaultfalse) - This will disable the objectify of the id field if you want to use normal strings
  • events (optional) - A list ofcustom service events sent by this service
  • paginate (optional) - Apagination object containing adefault andmax page size
  • whitelist (optional) - A list of additional query parameters to allow (e..g[ '$regex', '$geoNear' ])
  • multi (optional) - Allowcreate with arrays andupdate andremove withidnull to change multiple items. Can betrue for all methods or an array of allowed methods (e.g.[ 'remove', 'create' ])
  • useEstimatedDocumentCount (optional, defaultfalse) - Iftrue document counting will rely onestimatedDocumentCount instead ofcountDocuments

params.mongodb

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.

Transactions

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()}}})}

Example

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 mongodb

Inapp.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.

Querying

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.

Collation Support

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.

Example: Patch records with case-insensitive alphabetical ordering

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( ...);

Example: Find records with a case-insensitive search

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.

License

Copyright (c) 2019

Licensed under theMIT license.

About

A mongodb service for feathers

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors24


[8]ページ先頭

©2009-2025 Movatter.jp