Giter Club home page Giter Club logo

feathers-mongodb's Introduction

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

feathers-mongodb

CI Dependency Status Download Status

A Feathers database adapter for MongoDB using official NodeJS driver for MongoDB.

$ npm install --save mongodb feathers-mongodb

Important: feathers-mongodb implements the Feathers Common database adapter API and querying syntax.

This adapter also requires a running MongoDB database server.

API

service(options)

Returns a new service instance initialized with the given options. Model has to be a MongoDB collection.

const MongoClient = require('mongodb').MongoClient;
const service = 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, default false) - This will disable the objectify of the id field if you want to use normal strings
  • events (optional) - A list of custom service events sent by this service
  • paginate (optional) - A pagination object containing a default and max page size
  • whitelist (optional) - A list of additional query parameters to allow (e..g [ '$regex', '$geoNear' ])
  • multi (optional) - Allow create with arrays and update and remove with id null to change multiple items. Can be true for all methods or an array of allowed methods (e.g. [ 'remove', 'create' ])
  • useEstimatedDocumentCount (optional, default false) - If true document counting will rely on estimatedDocumentCount instead of countDocuments

params.mongodb

When making a service method call, params can contain an mongodb property (for example, {upsert: true}) which allows to modify the options used to run the MongoDB query.

Transactions

You can utilized a MongoDB Transactions by passing a session with the params.mongodb:

import { ObjectID } from 'mongodb'

export default async app => {
  app.use('/fooBarService', {
    async create(data) {
      // assumes you have access to the mongoClient via your app state
      let session = app.mongoClient.startSession()
      try {
        await session.withTransaction(async () => {
            let fooID = new ObjectID()
            let barID = new ObjectID()
            app.service('fooService').create(
              {
                ...data,
                _id: fooID,
                bar: barID,
              },
              { mongodb: { session } },
            )
            app.service('barService').create(
              {
                ...data,
                _id: barID
                foo: fooID
              },
              { mongodb: { session } },
            )
        })
      } finally {
        await session.endSession()
      }
    }
  })
}

Example

Here is an example of a Feathers server with a messages endpoint that writes to the feathers database and the messages collection.

$ npm install @feathersjs/feathers @feathersjs/errors @feathersjs/express @feathersjs/socketio feathers-mongodb mongodb

In app.js:

const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');

const MongoClient = require('mongodb').MongoClient;
const service = require('feathers-mongodb');

// Create an Express compatible Feathers application instance.
const app = express(feathers());
// Turn on JSON parser for REST services
app.use(express.json());
// Turn on URL-encoded parser for REST services
app.use(express.urlencoded({extended: true}));
// Enable REST services
app.configure(express.rest());
// Enable Socket.io
app.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 Express
app.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 connected
    app.service('messages').Model = client.db('feathers').collection('messages');

    // Now that we are connected, create a dummy Message
    app.service('messages').create({
      text: 'Message created on server'
    }).then(message => console.log('Created message', message));
  }).catch(error => console.error(error));

// Start the server.
const port = 3030;

app.listen(port, () => {
  console.log(`Feathers server listening on port ${port}`);
});

Run the example with node app and go to localhost:3030/messages.

Querying

Additionally to the common querying mechanism this adapter also supports MongoDB's query syntax and the update method also supports MongoDB update operators.

Important: External query values through HTTP URLs may have to be converted to the same type stored in MongoDB in a before hook 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, an age (which is a number) a hook like this can be used:

const ObjectID = 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;

      return Promise.resolve(context);
    }
  }
});

Which will allows queries like /users?_id=507f1f77bcf86cd799439011&age=25.

Collation Support

This adapter includes support for collation and case insensitive indexes available in MongoDB v3.4. Collation parameters may be passed using the special collation parameter to the find(), remove() and patch() 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'.

const patch = { shouldStudyMore: true };
const query = { grade: { $gte: 'c' } };
const collation = { 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.

const query = { grade: { $gte: 'c' } };
const collation = { locale: 'en', strength: 1 };
students.find({ query, collation }).then( ... );

For more information on MongoDB's collation feature, visit the collation reference page.

License

Copyright (c) 2019

Licensed under the MIT license.

feathers-mongodb's People

Contributors

adamvr avatar arlukin avatar claustres avatar corymsmith avatar daddywarbucks avatar daffl avatar davidnussio avatar ekryski avatar elisadaka avatar ericirish avatar gerigot avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jansel369 avatar joshuajabbour avatar joshuatoenyes avatar kulakowka avatar marshallswain avatar noobulater avatar pagury avatar rudolph9 avatar v1p avatar vincentexpotech avatar ydeshayes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

feathers-mongodb's Issues

how to insert?

I don't see any documentation on how to actually use the db connection for inserting (not querying)

maybe i'm just being a noob but I think the docs should define how one is to use this db connection...

Perfom an aggregation pipline

Can I build an aggregation pipeline via service.Model?
something like service.Model.aggregate([{'$sample': {'size': 1 }}]);

Query $in doesn't works with _id

Steps to reproduce

Make a query on the client:

app.service('users').find({
    _id: {
        $in: ["USER1_ID", "USER2_ID"]
    }
})

Or in REST : http://localhost:3030/users?_id[$in]=USER1_ID&_id[$in]=USER2_ID

With existing users ID;

Expected behavior

It should return users who are listed by their ID in $in property

Actual behavior

It return that no user match:
{"total":0,"limit":50,"skip":0,"data":[]}

Probably IDs should be converted anywhere

System configuration

MongoDB on linux 64 for the collection "users"

$ mongod --version
db version v3.6.1
git version: 025d4f4fe61efd1fb6f0005be20cb45a004093d1
OpenSSL version: OpenSSL 1.1.0g  2 Nov 2017
allocator: tcmalloc
modules: none
build environment:
    distarch: x86_64
    target_arch: x86_64

Module versions (especially the part that's not working) (On server):

$ npm list | grep mongo
β”œβ”€β”¬ [email protected]
β”œβ”€β”¬ [email protected]
β”‚ └─┬ [email protected]
$ npm list | grep feathers
β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”‚ β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ @feathersjs/[email protected]
β”œβ”€β”¬ @feathersjs/[email protected]
β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ @feathersjs/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ [email protected]
β”‚ β”œβ”€β”¬ [email protected]
β”œβ”€β”¬ [email protected]
β”œβ”€β”¬ [email protected] (git://github.com/feathers-plus/feathers-hooks-common.git#c99e4d51cbbf482f28137a574d61ef1b5a608363)
β”‚ β”œβ”€β”€ @feathers-plus/[email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”œβ”€β”¬ [email protected]
β”‚ β”œβ”€β”€ [email protected] deduped
β”‚ β”œβ”€β”¬ [email protected]
β”‚ β”‚ β”œβ”€β”¬ [email protected]
β”‚ β”‚ β”‚ └─┬ [email protected]
β”‚ β”‚ β”‚   β”œβ”€β”€ [email protected] deduped
β”‚ β”‚ β”‚   β”œβ”€β”¬ [email protected]
β”‚ β”‚ β”‚   β”‚ β”œβ”€β”€ [email protected]
β”‚ β”‚ β”‚   β”‚ β”œβ”€β”¬ [email protected]
β”‚ β”‚ β”‚   β”‚ β”‚ β”œβ”€β”€ [email protected] deduped
β”œβ”€β”¬ [email protected]
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped
β”‚ β”œβ”€β”€ @feathersjs/[email protected] deduped

NodeJS version:
v8.9.3
Operating System:
Linux x64 (AntergOS (Based on ArchLinux))

$select query field doesn't work in find() method

Expected behavior

.find() method should return results with specified fields from $select query

Actual behavior

It returns all the fields of docs

System configuration

Tell us about the applicable parts of your setup.

.find({ query: {
$select: [ 'firstName' ],
} })

// returns the data with all of its fields

This works in previous version of mongodb adapter with pretty much the same configuration.

Module versions (especially the part that's not working):
3.0.0

An in-range update of feathers-errors is breaking the build 🚨

Version 2.9.2 of feathers-errors just got published.

Branch Build failing 🚨
Dependency feathers-errors
Current Version 2.9.1
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

feathers-errors is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 6 commits.

  • 58bf260 2.9.2
  • ed53567 Adding package-lock.json
  • dc726ef fix typings (#87)
  • f0dbbce chore(package): update sinon to version 3.0.0 (#84)
  • 0f688d5 fix(package): update debug to version 3.0.0 (#86)
  • c44ce57 Updating changelog

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

the latest npm package is not updated?

Steps to reproduce

I might be wrong, but it's so weird that the npm package v2.8.0 is not the same with the latest repo on github. After npm i -S feathers-mongodb, the \lib\index.js#279 is:

return Promise.reject('Not replacing multiple records. Did you mean `patch`?');

but the same line in the repo forked from github's master branch (after compliation with npm test) is:

return Promise.reject(new _feathersErrors2.default.BadRequest('Not replacing multiple records. Did you mean `patch`?'));

The later one is OK, but the first one generates wrong format of error.

Expected behavior

Tell us what should happen

Actual behavior

Tell us what happens instead

System configuration

Tell us about the applicable parts of your setup.

Module versions (especially the part that's not working):
2.8.0
NodeJS version:
7.10.0
Operating System:
windows 10 with linux sub system
Browser Version:

React Native Version:

Module Loader:

How to unset a property of document

Hi, this plugin doesn't support $unset at mongodb so how to unset a property of document?

Currently work around:

  1. gets the complete object of document
  2. delete the property of object
  3. use UPDATE method to that document

Is there any better proper way?

Thanks.

Isn't update, patch, and remove supposed to support query like behavior?

I'm looking at the feathers docs here:
patch(id, data, params [, callback]) merges the existing data of the resource identified by id with the new data. id can also be null indicating that multiple resources should be patched.

It seems to me that you're supposed to be able to pass a null in for the id and then I suppose the query criteria would be in params?

Do the other feathers database adapters not work like this? It seems like it would just be a matter of using the collection.update function.

Is this on the agenda :). If not, maybe I'll take a crack at it next week.

How save date type string as ISODate type field?

I want save this 2017-11-24T11:52:57.000Z as ISODate("2017-11-24T11:52:57.000Z") on mongodb, which is getting save as string. How can i make it happen?

[edit]

ok i did this before passing data to service.create(data)

data.date = new Date(2017-11-24T11:52:57.000Z);
service.create(data)

is there any way to do this auto ? by checking if field's value is date type string ?

field constraint

Is there any way to ensure a field is unique in feathers mongodb?

Update/patch (PUT/PATCH) strips "id" from saved object

I'm still working on a test case, but I'm having issues with the update action. Not sure if it's in this module or another, but here are the details:

  • Using custom id field (id, not _id)
  • PUT /resources/123 with body {"id": "123", "title": "#123"} strips out the id field upon save.

This doesn't help, as it's not honored either; the id field is added to hook.data, but stripped again sometime before saving:

  service
    .before({
      update (hook) {
        // Copy ID from request into object.
        hook.data.id = hook.id
      }
  })

An in-range update of feathers is breaking the build 🚨

Version 2.2.0 of feathers just got published.

Branch Build failing 🚨
Dependency feathers
Current Version 2.1.7
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As feathers is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 7 commits.

  • aa87658 2.2.0
  • 1738993 Update package-lock.json
  • 7422757 No longer pollutes the global scope (#662)
  • a28ec8e fix(package): update debug to version 3.0.0 (#641)
  • e317dd5 Examples url is tinny (broken) (#634)
  • b57c80b Merge pull request #624 from jansel369/master
  • 8f40769 Adds a missing configure() method in typescript difinition

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of mocha is breaking the build 🚨

The devDependency mocha was updated from 6.0.1 to 6.0.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v6.0.2

6.0.2 / 2019-02-25

πŸ› Fixes

Two more regressions fixed:

  • #3768: Test file paths no longer dropped from mocha.opts (@boneskull)
  • #3767: --require does not break on module names that look like certain node flags (@boneskull)
Commits

The new version differs by 6 commits.

  • 00a895f Release v6.0.2
  • 1edce76 update CHANGELOG for v6.0.2 [ci skip]
  • 347e9db fix broken positional arguments in config; ensure positional args are unique; closes #3763
  • 9e31e9d fix handling of bareword args matching node flags; closes #3761
  • 6535965 Update "karma-browserify" to eliminate Karma middleware warning (#3762)
  • 37febb6 improve issue template. (#3411)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @feathersjs/adapter-commons is breaking the build 🚨

The dependency @feathersjs/adapter-commons was updated from 1.0.4 to 1.0.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@feathersjs/adapter-commons is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 2 commits.

  • c198e43 Publish
  • 2856722 fix: Update adapter common tests to check for falsy (#1140)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @feathersjs/adapter-commons is breaking the build 🚨

The dependency @feathersjs/adapter-commons was updated from 1.0.6 to 1.0.7.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@feathersjs/adapter-commons is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 3 commits.

  • 8c3a740 Publish
  • ed8c2e4 fix: Do not inherit app object from Object prototype (#1153)
  • 8e129d8 fix(chore): Add .npmignore to adapter-commons

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

npm install download incompatible MongoClient version

This is not a bug but now installing mongodb npm download the 3.0.0-rc0 version.
MongoClient.connect return client instead db.

The code generated with feathers-cli failed with the error:
TypeError: db.collection is not a function

  • Fix with downgrade mongodb version to 2.2.x
  • Fix follow the example below
const MongoClient = require('mongodb').MongoClient;
const service = 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 }));
});

$addToSet not working

I got the error message below when trying to use $addToSet in patching a document
error: GeneralError: The dollar ($) prefixed field '$addToSet' in '$addToSet' is not valid for storage.

Update method shows deprecation warning

Steps to reproduce

  • [] Generate basic feathers app (REST) with feathers-cli.
  • [] Generate new MongoDB service with feathers-cli.
  • [] Create new MongoDB database and collection, insert empty document.
  • [] Run a put request to the mongodb-service endpoint with document id.

Expected behavior

Document gets updated, no warning messages shown.

Actual behavior

Document gets updated, but a deprecation warning is shown:

DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead

Reason: The update method should use updateOne internally.

System configuration

Tell us about the applicable parts of your setup.

Module versions (especially the part that's not working):
"@feathersjs/express": "^1.2.6",
"@feathersjs/feathers": "^3.2.2",
"feathers-mongodb": "^3.3.0",
MongoDB 3.6.7

NodeJS version:
8.12.0

Operating System:
Linux Mint 18

An in-range update of @feathersjs/errors is breaking the build 🚨

The dependency @feathersjs/errors was updated from 3.3.5 to 3.3.6.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@feathersjs/errors is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 15 commits.

  • 8c3a740 Publish
  • ed8c2e4 fix: Do not inherit app object from Object prototype (#1153)
  • 8e129d8 fix(chore): Add .npmignore to adapter-commons
  • fa30617 Publish
  • c9f55d8 fix(adapter-commons): Keep Symbols when filtering a query (#1141)
  • c198e43 Publish
  • 2856722 fix: Update adapter common tests to check for falsy (#1140)
  • ae97020 Publish
  • 8166dda fix: Update adapter common tests (#1135)
  • 49164f4 Publish
  • 40402fc fix: Fix AdapterService multi option when set to true (#1134)
  • a6615d4 Publish
  • df1daaa fix: Add whitelist and filter support to common adapter service (#1132)
  • f83c28c Publish
  • cd1a183 fix: Throw error in filterQuery when query parameter is unknown (#1131)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

BadRequest: Invalid query parameter $geoWithin

{ location: { '$geoWithin': { '$centerSphere': [ [40.848688, -73.856029 ], 5/3963.2 ] } } }
I used the above query to find all locations around a specific location within 5 miles, it works when I ran the command in mongodb console but it threw this error in feathersjs:
error: BadRequest: Invalid query parameter $geoWithin

Gettting Page not found, Initial connect to db do not work?

Hello, i tried using this plugin with no succes

i have got this function

const service =  function() {
  const app = this;
  
  MongoClient.connect("mongodb://localhost:27017/feathers").then(client => {
    const db = client.db("EaCms");
    app.use(
      "/news",
      service({
        Model: db.collection("news")
      })
    );
  });
}

const app = feathers()

app
  .configure(hooks())
  .configure(rest())
  .configure(service)
  .configure(middleware);

export deafault app;

and i am getting

{
    "name": "NotFound",
    "message": "Page not found",
    "code": 404,
    "className": "not-found",
    "errors": {}
}

i tried doing this - commenting the connect part

const service =  function() {
  const app = this;
  /*
 MongoClient.connect("mongodb://localhost:27017/feathers").then(client => {
    const db = client.db("EaCms");
    app.use(
      "/news",
      service({
        Model: db.collection("news")
      })
    );
  });*/
 
 app.use("/testmongdb", function(req, res) {
    res.send(JSON.stringify(true));
  });
}

and i get the true response.

how use this plugin? what am i missing? is it because of connect that is async?

[Feature request] Support transactions

Transactions are available in Mongo V4: https://www.mongodb.com/transactions & https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html.

A way to ease implementing it is to provide:

  • before hook to start the transaction
  • an after hook to commit the transaction
  • an error hook to cancel the transaction

Because we also need to pass the transaction session into each DB call as well the module should also support passing it as a param and send it to Mongo operations.

_objectifyId / ObjectID.isValid converts legit string IDs to Mongo ObjectId

Steps to reproduce

  1. Assume a Mongo collection that has documents with _id fields of type string rather than ObjectId.
  2. Now try to get() a document with a string _id that ObjectID.isValid considers to be a valid ObjectId. E.g. service.get('my-string-id'). The call fails to find the document since the string "my-string-id" is cast to an ObjectId.

Actual behavior

The get() call fails since _objectifyId blindly casts a passed _id. Since the documents are stored with string _id values, the call fails to find the documents.

Expected behavior

The decision to cast a string _id to ObjectId or leave it as string should be configurable in the service options. The service allows you to configure the name of the "id" field, but not whether it should be casted. Note that the field MUST be named "_id" for Mongo to consider it a primary key anyway.

In short, it's possible to have a field named "_id" and have it be of the type string. _objectifyId should not cast it if you want it to remain as string.

Note

From the MongoDB manual: The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of ANY TYPE other than an array.

Need to return proper errors

For example:

  • Not Found
  • Bad Request
  • Internal Server Error
  • etc.

Feathers can then catch these errors and then proxy them back to client as it sees fit.

Support $search

This is a proposed special attribute that allows you to fuzzy match a property. Possibly even multiple properties and/or nested documents.

Suggested syntax:

name: {
  $search: ['alice', 'Alice', 'bo', /$bob/i]
}

Following similar syntax to our other special query filters, this would allow you to filter by a singular value, multiple values (treated like an or) and/or regular expressions directly.

Internally mongodb requires a $regex query but we can fairly easily build a singular regex from this array. Another internal construct that mongodb provides is $text so we might be able to use that for full text search.

No Open Connections

I'm getting a no open connections error fairly frequently while developing our app. I see on line 25 of your MongoService module that you specifically call out that you're creating a new connection for each service. Are you providing a mechanism to control the number of connections, or whether or not it can reuse an open connection rather than create a new one?

Replacing "_id" isn't possible, despite docs

If you set the optional _id parameter, it has no effect. All queries are still run against the default Mongo _id property.

I'll get this working as part of the Mongo 2 rewrite, but it might be a good idea to backport this fix. Or it might be too much work...

The dollar ($) prefixed field '$inc' in '$inc' is not valid for storage

Hi!

When I try to use $inc in the data field of patch method I get "The dollar ($) prefixed field '$inc' in '$inc' is not valid for storage.". Could I incrementing fields using $inc?

Steps to reproduce

  const data = {
    '$inc': {fieldName: 1}
  };
  return app.service('myService').patch(id, data);

System configuration

MongoDB: 3.4
feathers: 2.2.3
feathers-mongodb: 2.9.1

Upgrade to mongo-native 2.1

This might also eliminate the need for Mongoskin, though it depends on what you're using it for (mongo-native 2 supports promises).

MongoDB query needs to be flattened

I just discovered that when querying for nested objects in MongoDB like

{ something: { id: <id> } }

The final query object actually has to be flattened into

{ 'something.id': <id> }

Unique index on idField?

Should this adapter create a unique index on the idField (if it's not _id)? Or should that be up to the user to do manually out-of-band? Right now, if you set the idField to something else (like id), you can create multiple/duplicate documents with that id.

Still seeing the deprecation messages even after updating to 3.4.0

Steps to reproduce

(First please check that this issue is not already solved as described
here
)

  • Tell us what broke. The more detailed the better.
  • If you can, please create a simple example that reproduces the issue and link to a gist, jsbin, repo, etc.

Expected behavior

Tell us what should happen

Actual behavior

Tell us what happens instead

System configuration

Tell us about the applicable parts of your setup.

Module versions (especially the part that's not working):

NodeJS version:

Operating System:

Browser Version:

React Native Version:

Module Loader:

An in-range update of mongodb is breaking the build 🚨

Version 2.2.26 of mongodb just got published.

Branch Build failing 🚨
Dependency mongodb
Current Version 2.2.25
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mongodb is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ


Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details
Commits

The new version differs by 28 commits .

  • fce57db Updated version to V2.2.26
  • 27aa819 fix apm_tests to run on older node
  • e3f7242 NODE-983 Add cursorId to aggregate and listCollections commands
  • f204c37 Add cursor to reply of aggregate command (#1510)
  • 69ab14f fixed 0.10.x breaking code in runner.js
  • c54667c mark group and profilingInfo as deprecated methods
  • 70dffb8 [WIP] NODE-956 DOCS Examples (#1507)
  • 9497c7d Merge pull request #1505 from mongodb/greenkeeper-readable-stream-2.2.7
  • 4417c77 chore(package): update readable-stream to version 2.2.7
  • 1e9ce89 Merge pull request #1504 from tellnes/dirname
  • bcd5a72 NODE-978 Added test case to uncover connection.end issue for node 0.10.x
  • 9dce21a remove dynamic require
  • d81815e Merged
  • e10a9be NODE-696 Handle interrupted error for createIndexes
  • 13735ba Merge pull request #1502 from mbroadst/NODE-972

There are 28 commits in total. See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

need help extending mongodb

Hi, I'm trying to give the patch method an append functionality. I first get the data by id and check if it has type === "cost_chart". If so, I append value and call _super.patch. My problem is probably lack of js knowledge, that said, here is what I tried

  //uberproto extend
  ChartMongoDB = mongodb.Service.extend({
    patch: function(id, data, params, callback) {
      // I don't know how to call this._super inside the next function. This is what I tried without success
      var outer;
      outer = this;
      return this.collection.findById(id, params.query || {}, function(error, val) {
        var i, j, ref;
        console.log(outer); // at this point, outer._super is `undefined`
        if (error) {
          outer(id, data, params, callback);
        }
        // I only append if `cost_chart`
        if ((val != null ? val.type : void 0) === 'cost_chart') {
          // value should be a nested array
          for (i = j = 0, ref = data.value.length - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
            console.log(i, val.value[i], data.value[i]);
            val.value[i] = val.value[i].concat(data.value[i]); 
          }
          data.value = val.value;
          console.log('there', data); // right here I got exactly what I wanted, but how call _super with this new data?
        }
        return outer._super(id, data, params, callback);  // I got _super is not a function error
      });
    }
  });

If you read till this point first thank you and second do you have an idea on how to solve that problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.