Code Monkey home page Code Monkey logo

mongoose-q's Introduction

mongoose-q

DEPRECATED [ES6 Promise is supported]((http://mongoosejs.com/docs/harmony.html) by mongoose officially.

kriskowal's Q support for mongoose.

for mongodb native nodejs driver, see mongo-q.

usage

to apply Q with default suffix 'Q':

var mongoose = require('mongoose-q')(require('mongoose'));
// verbose way: mongooseQ is unused
var mongoose = require('mongoose'),
    mongooseQ = require('mongoose-q')(mongoose)
// shortest way: mongoose will be loaded by mongoose-q
var mongoose = require('mongoose-q')();

to apply another Q implementation(since v0.0.15):

// to use bluebird
var mongoose = require('mongoose-q')(require('mongoose'), {q:require('q-bluebird')});

use Q-applied model statics:

SomeModel.findByIdQ(....blahblah...)
  .then(function (result) { ... })
  .catch(function (err) { ... })
  .done();

use Q-applied model methods:

var someModel = new SomeModel(...);
someModel.populateQ()
  .then(function (result) { ... })
  .catch(function (err) { ... })
  .done();

use Q-applied query methods:

SomeModel.find(...).where(...).skip(...).limit(...).sort(...).populate(...)
  .execQ() // no 'Q' suffix for Query methods except for execQ()
  .then(function (result) { ... })
  .catch(function (err) { ... })
  .done();

use Q-applied aggregate methods:

SomeModel.aggregate(...).project(...).group(...).match(...).skip(...).limit(...).sort(...).unwind(...)
  .execQ() // no 'Q' suffix for Aggregate methods except for execQ()
  .then(function (result) { ... })
  .catch(function (err) { ... })
  .done();

to apply Q with custom suffix/prefix:

var mongoose = require('mongoose-q')(require('mongoose'), {prefix:'promiseOf_', suffix:'_withQ'});
SomeModel.promiseOf_findAndUpdate_withQ(...)
  .then(function (result) { ... })
  .catch(function (err) { ... })
  .done();

to apply Q with custom name mapper:

function customMapper(name) {
  return 'q' + name.charAt(0).toUpperCase() + name.substring(1);
}
var mongoose = require('mongoose-q')(require('mongoose'), {mapper:customMapper});
SomeModel.qFindAndUpdate(...)
  .then(function (result) { ... })
  .catch(function (err) { ... })
  .done();

DEPRECATED to apply Q with spread:

NOTE: since mongoose 4.x: no spread for update()!

NOTE: without spread option(by default), you can access only the first result with then!!

var mongoose = require('mongoose-q')(require('mongoose'), {spread:true});
SomeModel.createQ(doc1, doc2, ...)
  .spread(function (saved1, saved2, ...) { ... })
  .catch(function (err) { ... })
  .done();
SomeModel.createQ(doc1, doc2, ...)
  .then(function (result) { var saved1 = result[0], raw = saved1[1]; ... })
  .catch(function (err) { ... })
  .done();
...
var model = new SomeModel();
...
model.saveQ()
  .spread(function (savedDoc, affectedRows) { ... })
  .catch(function (err) { ... })
  .done();
...
model.saveQ()
  .then(function (result) { var savedDoc = result[0], affectedRows = result[1]; ... })
  .catch(function (err) { ... })
  .done();

to define custom statics/instance methods using Q

NOTE: this is not a feature of mongoose-q

SomeSchema.statics.findByName = function (name) {
  return this.findQ({name: name}); // NOTE: returns Promise object.
};
...
var SomeModel = mongoose.model('Some', SomeSchema);
SomeModel.findByName('foo').then(function(result) {
  console.log(result);
});

That's all folks!

mongoose-q's People

Contributors

colinphanna avatar gerarde avatar iolo avatar suprememoocow 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

mongoose-q's Issues

Aggregate#exec is not wrapped

When Model.aggreate is called with no callback, it gives you an instance of Aggregate that you can build up a query and call exec on like Query, but unfortunately it's not exposed off of the mongoose singleton so it's not easy to get too. Probably needs special case patching of Model.aggregate to handle that optioncal callback. Currently the wrapped aggregateQ always ends up adding the callback and can never hit that other branch to allow you to build up a query then execute it promise-style.

mongoose 3.6.15 issues

When upgrading from mongoose 3.6.14 to 3.6.15 calls to the mongoose-q Q() methods never resolve/reject the promise. Also setting mongoose.set('debug', true); does not dump debug upon connect, like it does in 3.6.14.

I'm a node noob so its kinda hard for me to track down. Have you run into this yet?

here is my dependencies:

  "dependencies": {
    "geddy": "0.9.x",
    "jake": "0.5.x",
    "mocha":"1.12.x",
    "passport": "0.1.x",
    "bcrypt": "0.7.x",
    "q": "0.9.x",
    "facebook-node-sdk": "0.2.x",
    "request": "2.21.x",
    "memcached": "0.2.x",
    "node-uuid": "1.4.x",
    "underscore": "1.4.x",
    "mongoose": "=3.6.15",
    "mongoose-q": "0.0.4",
    "validator": "1.2.x"
  }

If I rm -rf node_modules && npm cache clear then update my package.json to "mongoose": "=3.6.14", then do npm install things work just fine.

calling populateQ() more than once?

I have to nest the call now, i'm just wondering if there is an easier way:

    Job
        .populateQ(job, { path: 'creator', select: '-salt -hashedPassword -email' })
        .then(function(job){
            job = utils.getJobPerms(job, user);
            job = utils.job.getCreatorProfile(job);

            Job
                .populateQ(job, { path: 'skillTags roleTags'})
                .then(function(job){
                    job.skillTags = utils.getTagPerms(job.skillTags, user);
                    job.roleTags = utils.getTagPerms(job.roleTags, user);

                    res.json(job);
                });
        });

SaveQ does not call middleware

Schema.pre('save', function (next) {
    console.log('testing');
    next();
}

Calling document.saveQ() does not invoke the middleware.

node.js version

When I run npm install, I have this warning:

npm WARN engine [email protected]: wanted: {"node":"~0.10"} (current: {"node":"0.12.1","npm":"2.7.3"})

Mongoose-q works really well with node 0.12, so I think you can update the required version.

model.createQ not working when creating with an array

In some of my tests I'm trying to create multiple documents by passing them as an array to Model.createQ. Unfortunately when I use Model.createQ my then is only getting the first document as an argument. When I switch things to use the normal mongoose create I get both documents. Here's the code I'm using in both cases:

using mongoose-q

User.createQ([
  { username: 'Julian' },
  { username: 'ricky' }
]).then(function() {
  console.log('here --->', arguments);
});

using stock mongoose

User.create([
  { username: 'Julian' },
  { username: 'ricky' }
]).then(function() {
  console.log('here --->', arguments);
});

Calling custom statics

In my application I'm using custom statics like this from the mongoose-docs:

// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
  this.find({ name: new RegExp(name, 'i') }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
  console.log(animals);
});

Am I missing something or is it impossible to call these custom methods with a Q suffix?TypeError: Object function model(doc, fields, skipId) {
if (!(this instanceof model))
return new model(doc, fields, skipId);
Model.call(this, doc, fields, skipId);
} has no method 'findByUsernameQ'

Animal.findByName('fido').then(function(animal) {
  console.log(animals);
});

I'm getting this error:

TypeError: Object function model(doc, fields, skipId) {
    if (!(this instanceof model))
      return new model(doc, fields, skipId);
    Model.call(this, doc, fields, skipId);
  } has no method 'findByNameQ'
...

BDD style tests with Mocha + Chai

I'm finding it a bit hard to read the tests - are you interested in having them rewritten with Mocha + chai? they should be alot more readable and mocha-as-promised may help here too.

Also, Grunt isn't doing much either, but that's a bit different.

Using unstable releases of mongoose

In package.json, you specify the version range ^3.8.3 for mongoose. That includes 3.9.x, which is currently unstable (a big warning appears in terminal output when running anything using such a version). It should probably be ~3.8.3, which will stay within 3.8.x.

If you agree, I'll gladly check that the warning indeed goas away, and issue a PR.

model.saveQ() example incorrect

model.saveQ()
  .then(function (result) { var savedDoc = result[0], affectedRows = result[1]; ... })
  .catch(function (err) { ... })
  .done();

However, result is not an array, but is an Object (the savedDoc itself).

Why is Query.populate not supported?

I noticed the lack of Query.populate support. When I tried to simply add "populate" to MONGOOSE_QUERY_METHODS, the promises are never resolved.

To demonstrate what I've been working with:

Code before mongoose-q:

Q.ninvoke( Person.model.find().populate( "messages" ), "exec" )

Naive attempt:

Person.model.findQ().populate( "messages" )

Results in: TypeError: Object [object Promise] has no method 'populate'

Adding populate to MONGOOSE_QUERY_METHODS

Person.model.find().populateQ( "messages" )

Never resolves

aggregate function exec not getting hooked in mongoose 4.0.5

For example:

return mongoose.model("Model")
    .aggregate(
      { $sort: { "modifiedAt": -1 } },
      {
        $group: {
          _id:          '$uuid',
          id:           { $first: '$uuid'         },
          name:         { $first: '$name'         },
          modifiedAt:   { $first: '$modifiedAt'   },
          createdAt:    { $first: '$createdAt'    },
        }
      }
    )
    .execQ();

Mongoose Q for multiple databases

I have two mongo database instances to connect to. For this reason, I have to use:
conn1 = mongoose.createConnection('localhost', "db-name-1");
conn2 = mongoose.createConnection('localhost', "db-name-2");

Then to create mongoose model, I have to use:
conn1.model(modelName, modelSchema) instead of using mongoose.model(modelName,
modelSchema),

I did put var mongoose = require('mongoose-q')() at the beginning of the file; but it seems that i doesn't work as expected. More specifically, old mongoose syntax (without Q suffix working fine), but new one such as modelObj.createQ(item) does not working. It doesn't even throw error. I guess because the connection pool is different.

How I can make mongooseQ to work in case I need to maintain 2 connection pools (each with different model set)?

Thanks.

aggregate workaround is not working

The require path to the aggregate lib of mongoose is not correct. Is should be:

qualify(require(path.resolve(__dirname + '/../../mongoose/lib/aggregate')).prototype

(where path is the path module from nodejs) instead of:

qualify(require(__dirname + '/../node_modules/mongoose/lib/aggregate').prototype

because [1] to use path.resolve is just cleaner and [2] the require is inside the libs folder, so you have to go two directories up to access the node_modules folder.

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.