Code Monkey home page Code Monkey logo

mongoose's Introduction

Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha).

Build Status NPM version Deno version Deno popularity

npm

Documentation

The official documentation website is mongoosejs.com.

Mongoose 8.0.0 was released on October 31, 2023. You can find more details on backwards breaking changes in 8.0.0 on our docs site.

Support

Plugins

Check out the plugins search site to see hundreds of related modules from the community. Next, learn how to write your own plugin from the docs or this blog post.

Contributors

Pull requests are always welcome! Please base pull requests against the master branch and follow the contributing guide.

If your pull requests makes documentation changes, please do not modify any .html files. The .html files are compiled code, so please make your changes in docs/*.pug, lib/*.js, or test/docs/*.js.

View all 400+ contributors.

Installation

First install Node.js and MongoDB. Then:

npm install mongoose

Mongoose 6.8.0 also includes alpha support for Deno.

Importing

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

Or, using Deno's createRequire() for CommonJS support as follows.

import { createRequire } from 'https://deno.land/[email protected]/node/module.ts';
const require = createRequire(import.meta.url);

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test')
  .then(() => console.log('Connected!'));

You can then run the above script using the following.

deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js

Mongoose for Enterprise

Available as part of the Tidelift Subscription

The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Overview

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

await mongoose.connect('mongodb://127.0.0.1/my_database');

Once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.

Important! Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.

Defining a Model

Models are defined through the Schema interface.

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const BlogPost = new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:

The following example shows some of these features:

const Comment = new Schema({
  name: { type: String, default: 'hahaha' },
  age: { type: Number, min: 18, index: true },
  bio: { type: String, match: /[a-z]/ },
  date: { type: Date, default: Date.now },
  buff: Buffer
});

// a setter
Comment.path('name').set(function(v) {
  return capitalize(v);
});

// middleware
Comment.pre('save', function(next) {
  notify(this.get('email'));
  next();
});

Take a look at the example in examples/schema/schema.js for an end-to-end example of a typical setup.

Accessing a Model

Once we define a model through mongoose.model('ModelName', mySchema), we can access it through the same function

const MyModel = mongoose.model('ModelName');

Or just do it all at once

const MyModel = mongoose.model('ModelName', mySchema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. For example, if you use

const MyModel = mongoose.model('Ticket', mySchema);

Then MyModel will use the tickets collection, not the ticket collection. For more details read the model docs.

Once we have our model, we can then instantiate it, and save it:

const instance = new MyModel();
instance.my.key = 'hello';
await instance.save();

Or we can find documents from the same collection

await MyModel.find({});

You can also findOne, findById, update, etc.

const instance = await MyModel.findOne({ /* ... */ });
console.log(instance.my.key); // 'hello'

For more details check out the docs.

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model('ModelName', schema);
const m = new MyModel();
await m.save(); // works

vs

const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const m = new MyModel();
await m.save(); // does not work b/c the default connection object was never connected

Embedded Documents

In the first example snippet, we defined a key in the Schema that looks like:

comments: [Comment]

Where Comment is a Schema we created. This means that creating embedded documents is as simple as:

// retrieve my model
const BlogPost = mongoose.model('BlogPost');

// create a blog post
const post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

await post.save();

The same goes for removing them:

const post = await BlogPost.findById(myId);
post.comments[0].deleteOne();
await post.save();

Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.

Middleware

See the docs page.

Intercepting and mutating method arguments

You can intercept method arguments via middleware.

For example, this would allow you to broadcast changes about your Documents every time someone sets a path in your Document to a new value:

schema.pre('set', function(next, path, val, typel) {
  // `this` is the current Document
  this.emit('set', path, val);

  // Pass control to the next pre
  next();
});

Moreover, you can mutate the incoming method arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to next:

schema.pre(method, function firstPre(next, methodArg1, methodArg2) {
  // Mutate methodArg1
  next('altered-' + methodArg1.toString(), methodArg2);
});

// pre declaration is chainable
schema.pre(method, function secondPre(next, methodArg1, methodArg2) {
  console.log(methodArg1);
  // => 'altered-originalValOfMethodArg1'

  console.log(methodArg2);
  // => 'originalValOfMethodArg2'

  // Passing no arguments to `next` automatically passes along the current argument values
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  // and also equivalent to, with the example method arg
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  next();
});

Schema gotcha

type, when used in a schema has special meaning within Mongoose. If your schema requires using type as a nested property you must use object notation:

new Schema({
  broken: { type: Boolean },
  asset: {
    name: String,
    type: String // uh oh, it broke. asset will be interpreted as String
  }
});

new Schema({
  works: { type: Boolean },
  asset: {
    name: String,
    type: { type: String } // works. asset is an object with a type property
  }
});

Driver Access

Mongoose is built on top of the official MongoDB Node.js driver. Each mongoose model keeps a reference to a native MongoDB driver collection. The collection object can be accessed using YourModel.collection. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one notable exception that YourModel.collection still buffers commands. As such, YourModel.collection.find() will not return a cursor.

API Docs

Find the API docs here, generated using dox and acquit.

Related Projects

MongoDB Runners

Unofficial CLIs

Data Seeding

Express Session Stores

License

Copyright (c) 2010 LearnBoost <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mongoose's People

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

mongoose's Issues

npm?

Hello, I was told to come here and bug you to put your package in the npm registry? Can you please do that? Thank you, Mongoose is awesome!

hydrate not working ?

this doesn't work ?

u = new User({nick:"john", pass:"1234"})
u.save() # end up with a document in mongo that's got undefined properties

but this does ?

u =new User()
u.nick = "jon" 
u.pass = "1234"
u.save()

?

save doesn't work

Hi,
I can't figure out why it doesn't work:

var mongoose = require('mongoose/lib/core').Mongoose,
db = mongoose.connect('mongodb://localhost/test'),
Test = db.model('Test', {
properties: ['first', 'second', 'third']
});

in function:

var a = {'first':'sometext', 'second':'sometext', 'third':'sometext'},
b = new Test(a);
b.save(function(){
res.simpleBody('200', sys.inspect(b));
});

as result I can see object b:

{ __doc: { _id: { id: 'L9\u00b6K+\u00daH@\u0005\u0000\u0000\u0001' } }
, isNew: false
, _dirty: {}
, first: 'sometext'
, second: 'sometext'
, third: 'sometext'
}

but nothing is saved in database except id:
{"_id": ObjectId("somehex")}
i.e. it "saves" only id of object, but no other properties.
Am I doing something wrong?

Doesn't work with Kiwi installer

$ kiwi install mongoose [that works]
node>var kiwi = require('kiwi');
node>kiwi.require('mongoose');
Error: Cannot find module 'mongoose'

Thanks

Uncaught, unspecified error event

Uncaught, unspecified 'error' event.
at Object.emit (events:13:15)
at Object. (/Users/deepu/Sites/mongoose/lib/storage.js:22:22)
at /Users/deepu/Sites/mongoose/lib/utils/proto.js:13:19
at /Users/deepu/Sites/mongoose/lib/utils/proto.js:14:6
at [object Object]. (/Users/deepu/Sites/mongoose/lib/support/mongodb/lib/mongodb/db.js:51:11)
at [object Object].emit (events:32:26)
at [object Object]. (/Users/deepu/Sites/mongoose/lib/support/mongodb/lib/mongodb/db.js:73:37)
at [object Object].emit (events:25:26)
at Stream. (/Users/deepu/Sites/mongoose/lib/support/mongodb/lib/mongodb/connection.js:82:16)
at Stream.emit (events:25:26)

node version 0.1.95 . all i did is git clone mongoose, cd mongoose, git submodule init, git submodule update and then ran a simple test which is giving this error. Am i missing something ???

mongoose incompatible with node-mongodb-native V0.8.0

I don't have time to figure out why, but I believe that BSONNative or BSONPure needs to be imported for it to work.. additionally, teh native driver needs to be built in the mongoose Makefile.

to workaround the issue for now, go to lib/support/node-mongodb-native/ and type "git checkout V0.7.9"

make test fails with the latest!

cginzel@vmubuntu03:~/mongoose$ make test


sys:319
    ctor.prototype = Object.create(superCtor.prototype, {
                            ^
TypeError: Object prototype may only be an Object or null
    at Function.create (native)
    at Object.inherits (sys:319:29)
    at Object. (lib/core.js:77:5)
    at Module._compile (module:384:23)
    at Module._loadScriptSync (module:393:8)
    at Module.loadSync (module:296:10)
    at loadModule (module:241:16)
    at require (module:364:12)
    at Object. (mongoose.js:3:17)
    at Module._compile (module:384:23)
make: *** [test] Error 11

model.properties define empty layout structure

If I have a collection like this::
{
UID: 1,
T: {
ts_17546: [17546, 0, 0],
ts_17606: [17606, 2, 1]
}
}

//setup collection model
mongoose.model('test',{
collection:'test',
properties: ['UID', 'VID', {'T':{[]}}] //this is wrong? what should it be?
});

//set model
test = db.model('test');

//insert new
var tileSet = 'myTest'//name or array
var t= new test();
t.UID = 101;
t.T[tileSet] = ['1x','2x','3x'];
t.save();

code for Model.update() and some minor bug fixes...

I've added this update method to the Model class so that I can issue an update which will only apply the properties I'm passing instead of having to apply a whole hydrated object and it then returns the current value in the db which should include the passed updates. This way the latest record can be passed back for display including any other changes that may have been done by someone else. Also you were missing the self declaration in both remove and count used when there is an error.

    update: function(id, doc, fn){
      var self = this;
      id = (id instanceof ObjectID || id.toHexString) ? id : ObjectID.createFromHexString(id);
      this._collection.update({_id: id}, {$set: doc}, {upsert: false, safe: true}, function(err){
        if (err) return self._connection._error(err);
        if (fn) return self.findById(id, fn, true);
      });
      return this;
    },

    remove: function(where, fn){
      var self = this;
      this._collection.remove(where || {}, function(err){
        if (err) return self._connection._error(err);
        fn();
      });
      return this;
    },
    
    count: function(where, fn){
      var self = this;
      this._collection.count(where || {}, function(err, count){
        if (err) return self._connection._error(err);
        fn(count);
      });
      return this;
    }

Mongoose breaking with node v0.1.100

Hey guys,
I ran into this issue today using HEAD and the above node version. I'm also using the latest express.js framework.

TypeError: Object prototype may only be an Object or null
at Function.create (native)
at Object.inherits (sys:319:29)
at Object. (/code/mongoose/lib/core.js:78:5)
at Module._compile (module:381:21)
at Module._loadScriptSync (module:390:8)
at Module.loadSync (module:296:10)
at loadModule (module:241:16)
at require (module:364:12)
at Object. (
/code/mongoose/mongoose.js:3:17)
at Module._compile (module:381:21)

Any help would be greatly appreciated.

Thanks.

subsets not working?

hi,

I try to get a subsed of fields using:

GW.find({'data.Gateway.xmpp_user': jid.user}, {'data.Gateway.issues':0}).first(function(gw){
console.log("found gw");
console.log(gw);
});

but it always returns the whole object. is it a bug in mongoose?

thx, best, danielzzz

activeStore

I don't really understand how activeStore works. Is the example you gave right? Could you maybe flesh it out a little? thanks,
bp

$in value stripped when querying _id

Neither of these queries return results.

model.find({id: {$in: ['4c4468976bdfe50b7b0dd1b2', ...]}})
model.find({id: {$in: [ObjectID.createFromHexString('4c4468976bdfe50b7b0dd1b2'), ...]}})

The ids are stripped when the values are cast in query.js line 22 so when the object is passed to node-mongodb-native the value of _id is an empty ObjectID.

noSchema does not exist

The intros at http://www.learnboost.com/mongoose/ and http://labs.learnboost.com/mongoose/ reference mongoose.noSchema. It doesn't exist:

node> sys.puts(sys.inspect(mongoose));
{ _config: { log: true }
, _models: {}
, _connections: 
   { 'mongodb://localhost/test': 
      { base: [Circular]
      , uri: [Object]
      , name: 'test'
      , _compiled: {}
      , _collections: {}
      , db: [Object]
      , _events: [Object]
      , _connected: true
      }
   }
, connect: [Function]
, model: [Function]
, _open: [Function]
, _onError: [Function]
, _lookup: [Function]
, set: [Function]
, enable: [Function]
, disable: [Function]
, super_: 
   { emit: [Function]
   , addListener: [Function]
   , removeListener: [Function]
   , removeAllListeners: [Function]
   , listeners: [Function]
   }
, prototype: { constructor: [Circular] }
}

Are those docs out of date?

Support big integers

I have an integer like : 12345678912
it looks fine in mongo, but comes out as null in mongoose.
if the numbers 123456789 then it's ok.

mapReduce

Is there any way to do a mapReduce through Mongoose?
http://www.mongodb.org/display/DOCS/MapReduce

Including mongo (from the native driver) I've gotten as far as:
var reduce = new mongo.Code("function (key, values) { return Math.min.apply(Math, values); }");
var map = new mongo.Code("function () { emit(new Date(this.created_at).toLocaleDateString(), this.total); }");

db.collection('measurement').mapReduce(map, reduce, function(err, coll) {
...
});

validations

Hi - I'm trying and failing to do some validation code (e.g unique nick, suitable password, regex email).

Would you mind providing a little bit of sample code showing how to do this ?

Can I set `_id` by myself?

Hi guys,

I need to set _id with my own method instead of ObjectId provided by mongodb, can I do this with mongoose. (i can use something like id or key, but i don't want to waste a column)

Saving only includes _id

This is similar to another issue I saw posted here, but the reporter seems to have gotten it to work via hydrating. That doesn't work for me. I have this coffeescript:

https://gist.github.com/0aad3d4fe2e612f917d0

And it only saves the _id, no matter what I can think to try. I've removed the property from the new call and made it "u.jid =...". I've passed true, false and null in for the hydrate arg of the constructor. I've quoted and unquoted properties. I even compiled the coffeescript to JS and nothing looks odd about it.

Would really appreciate help with this. I've been struggling with this particular issue for hours and can't seem to figure it out.

How to use count() ?

I tried many things but I can't make count() work.
Based on the documentation, it is supposed to work this may:
User.find({username: 'john'}).count()

I've got this error:
DEBUG: TypeError: undefined is not a function
at CALL_NON_FUNCTION (native)
at /lib/mongoose/lib/model.js:177:9

I've also tried with
User.find({username: 'john'}).count(fn(r) { sys.debug(r); })
Or
User.count();
...

Thanks for your support.

Docs Request

I'm very interested in using this library to power a experimental video site. But I am not following the blog example very well, could you add an additional example that shows updated "references:" to reflect the nesting of the posts?

should fail on unique index?

Hi I'm trying add a unique index - which seems to work. But it still seems to call the "save" callback, even though it's not being added? Is there an fail callback ?

Saving an id to a custom column fails

I have a model with a field called '_account', which should default to a type of ObjectID. When I create a new instance and try to set '_account' to the '_id' of another object, it applies correctly to the object, but when I save the object, that field '_account' remains blank, and the type is reported as String.

is _this_ correct?

I added a line to your example:

methods: {
  save: function (fn) {
    this.updated_at: new Date()
    sys.p(this.isNew())
    this.__super__(fn)
    }
    }

which gives

sys.p(this.isNew());
                   ^
TypeError: Property 'isNew' of object [object Object] is not a function

Is it getting called in the correct context? It's being called from line 167 in utils.js

Binding as module

I have little bit difficult folder structure in my project. So if i try to bind mongoose as module it doesn't work. I have to add index.js to the mongoose root folder to get module be load.

Here is my initial index.js file content:
http://gist.github.com/425190

express + mongoose + mongohq

Hey guys,
I'm trying to make express, mongoose and mongohq playing together for few hours now and cannot make it working, here's an example code, do you see anything wrong :

    //Module dependencies.
    require.paths.unshift('vendor/mongoose');

    var sys       = require("sys")
        express   = require('express'),
        connect   = require('connect');
    var mongoose = require('mongoose').Mongoose;

    mongoose.model('User', {
        properties: ['first', 'last', 'age']
    });

    var db = mongoose.connect('mongodb://login:[email protected]:27074/smk');
    var User = db.model('User');

    // Create and export Express app

    var app = express.createServer();

    // Configuration

    app.configure(function(){
        app.set('views', __dirname + '/views');
        app.use(connect.logger());
        app.use(connect.bodyDecoder());
        app.use(connect.methodOverride());
        app.use(connect.compiler({ src: __dirname + '/public', enable: ['sass'] }));
        app.use(connect.staticProvider(__dirname + '/public'));
    });

    app.configure('development', function(){
        app.set('reload views', 1000);
        app.use(connect.errorHandler({ dumpExceptions: true, showStack: true })); 
    });

    app.configure('production', function(){
       app.use(connect.errorHandler()); 
    });

    // Routes

    app.get('/', function(req, res){
      var u = new User({first: 'John', last: 'Doe', age: 18});
      u.save(function(){
        res.render('index.jade', {
          locals: {
            title: 'Hello world'//sys.inspect(array)
          }
        });
      });
    });

    app.listen(3000);

When I hit localhost:3000, the request works but nothing has been created

sync ?

someone on #node.js was saying that mongoose was synchronous in some way. I was saying otherwise - i.e. non-blocking. Can you clear it up either way ?

Strange issue with Collection names

Using the following code, my collection name is always appended by an s for some reason. This is whilst attempting to use a noschma model.

var sys = require('sys');
var mongoose = require('./mongoose/mongoose').Mongoose;
var database = mongoose.connect('mongodb://localhost/randomvaldb');
var randomVals = database.model('valdatas');

The randomVals model is mapped to valdatass instead of valdatas.

Accessing MongoDB Native

In your blog post you talked about being able to access the mongodb-native by accessing db.Model.collection. This doesn't seem to work anymore.

Can you please give an example on how we can fall back to MongoDB Native. For example, right now I need to only fetch a subset of an object, which isn't supported by Mongoose yet.

So I was thinking of just manually fetching the object using MongoDB Native, but there's no easy way to access the substrate :/

.remove() doesn't work

db.stories.findByPermalink(permalink).first(function(r) {
// r = MongooseModel object 
r.remove(); // Mongoose thinks r is a new document and returns
});

I could make this work by commenting the lines in mongoose/lib/model.js

  remove: function(fn){
    /*
    if (this.isNew){
      if (fn) fn();
      return this;
    }
    */
    this._collection.remove({ _id: this.__doc._id }, fn);
    return this;
  },

Problems with sorting

Hi,

I tried to use sorting in a query. I first tried something like
Model.find(...).sort({'column' : 1}) from the mongodb documentation
then Model.find(...).sort(['column' : 1]) as written in unit tests (/tests/unit/spec.lib.query.js),
but no results were returned.
At last, tried Model.find(...).sort([['column', 1]]), which worked.
Is it normal ? If so, maybe the documentation and/or the unit test could be updated ?

Thanks

Problem in QueryPromise's atomic functions

Here is a fixed version of QueryPromise's atomic functions that place the command and arguments in the correct place.
// atomic similar

  ['inc','set','unset','push','pushAll',
  'addToSet','pop','pull','pullAll'].forEach(function(cmd){
      QueryPromise.prototype[cmd] = function(modifier){
        if(this.op.name.charAt(0) != 'u') return this;
        if(!this.op.args.length) this.op.args.push({},{});
        if(this.op.args.length == 1) this.op.args.push({});
        for(i in modifier) {
          if(!(this.op.args[1]['$'+cmd] instanceof Object)) this.op.args[1]['$'+cmd] = {};
          this.op.args[1]['$'+cmd][i] = modifier[i];
        }
        return this;
      }
  });

Here is a test program:
// Simple test program to show a problem in QueryPromise
// ['inc','set','unset','push','pushAll','addToSet','pop','pull','pullAll']

var sys = require('sys')
var mongoose = require('mongoose/').Mongoose
var db = mongoose.connect('mongodb://localhost/test');

var Simple = mongoose.noSchema('test',db);
Simple.drop(); 
//should only be one....
var m = new Simple({name:'test', x:0,y:0}).save()
// these should behave the same
Simple.update({name:'test'},{'$inc':{x:1, y:1}}).execute();
Simple.update({name:'test'}).inc({x:1, y:1}).execute();
Simple.update({name:'test'}).inc({x:1}).inc({y:1}).execute();

Simple.find({name:'test'}).each(
     function (doc) {
         sys.puts(JSON.stringify(doc));
     }
).then(
    function(){ // promise (execute after query)
        Simple.close(); // close event loop
    }
);

Error with JSON.stringify on a result array

Doesn't work: it returns each result as a full string (hence double quotes around keys are escaped by JSON.stringify):
stories.find().limit(20).all(function(r) {
self.halt(200,JSON.stringify(r));
});

Workaround to make it work:
stories.find().limit(20).all(function(r) {

    var result=[];
    for (var i=0; i < r.length; i++) {
        var o = {};
        for(var key in r[i]) {
            o[key] = r[i][key];
        }
        result.push(o);
    };

    self.halt(200,JSON.stringify(result));

});

Have you also experienced this issue?
Thanks for your support.

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.