Code Monkey home page Code Monkey logo

mongoose's Issues

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.

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

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.

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

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

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

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) {
...
});

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!

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 ?

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

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.

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.

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"

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.

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)

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

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

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

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?

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

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?

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

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.

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 ?

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?

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

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

.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;
  },

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 ?

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

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

?

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.