Kevin Smith | 22 May 15:09
Gravatar

Save failing without error

I have a model with a `index: {unique: true}`. The index is working and preventing duplicates in the database but I don't get an error when the save fails. What could cause this?

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
Michael Yagudaev | 20 May 23:54
Picon
Gravatar

Simple Unit Testing

I would like to request some documentation be added to the public web page that explains the simplest setup for unit testing. Unit testing with Expresso and NodeUnit should be explained.


I tried to do this myself, but I was unsuccessful so far. By a simple setup I mean, create a test database do operations on it during one test case and then drop it. Currently we are using Expresso, but we are open to switching to NodeUnit.

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
David D. | 20 May 21:57
Picon
Gravatar

Creating a model interpretor

Hello,

I'm writing an app that will translate a model definition for another
non-Node framework. I'm curious if I'm doing something wrong or if
there might be a bug in the latest build.

My app.js looks like so:

// Require global libraries
mongoose = require('mongoose');
config   = require('../../config.json');
require('./models.js');

// Require scoped libraries
var restify  = require('restify'),
	app   = restify.createServer(config.api);

// General API router
app.get(
	{ path: '/api/:parcel/:api_controller', version: '1.0.0' },
	function(request, response, next) {
		var controller = require(
			'../' + request.params.parcel + '/api/' +
request.params.api_controller
		);
		controller.index(request, response, next);
		response.end();
	}
);
app.listen(3000);

My model class looks like:

Model = function(parcel, name) {

	var model_name = name;
	var schema     = null;
	var parcel     = parcel;
	var model      = null;
	var db         = null;
	var fields     = null;

	this.init = function() {
		// Get the model definition from the proper folder
		var schema = require('../' + parcel + '/models/' + name + '.json');

		// Establish the database connection for this class
		db = mongoose.connect(
			'mongodb://' + config.database.DB_HOST + '/' +
config.database.DB_NAME
		);
		console.log(this.convert_fields(schema.fields));
		// Setup the mongoose model
		model = db.model(
			model_name,
			new mongoose.Schema(this.convert_fields(schema.fields))
		);
	}

        // Translates the old schema definition to Mongoose friendly
schema
	this.convert_fields = function(fields) {
		var converted_fields = {};
		for (var i in fields) {

			converted_fields[i] = {};
			converted_fields[i]['default'] = 'test';
			converted_fields[i]['required'] = true;

			// Convert the field types
			switch (fields[i].type) {
				case 'TEXT':
					converted_fields[i].type = mongoose.Schema.Types.String;
					break;
				case 'DATE':
					converted_fields[i].type = mongoose.Schema.Types.Date;
					break;
				case 'ENUM':
					converted_fields[i].enum = fields[i].value.replace(/'/g,
'').split(',');
					break;
				case 'INT':
					converted_fields[i].type = mongoose.Schema.Types.Number;
					break;
			}
		}
		return converted_fields;
	}
}

It's throwing errors when trying to define a type, default, enum or
required at the schema level. The message I'm getting is: "Undefined
type at `email`\n Did you try nesting Schemas? You can only nest using
refs or arrays.". This happens when I'm throwing the fields into the
Schema class on:

new mongoose.Schema(this.convert_fields(schema.fields))

When I output converted_fields (the transformed model), I see it's
been generated correctly:

{
    email: {
        type: [Function: SchemaString]
    },
    first_name: {
        type: [Function: SchemaString]
    },
    last_name: {
        type: [Function: SchemaString]
    },
    password: {
        type: [Function: SchemaString]
    },
    status: {
        enum: ['active', 'inactive']
    },
    created_at: {
        type: [Function: SchemaDate]
    },
    updated_at: {
        type: [Function: SchemaDate]
    },
    last_login: {
        type: [Function: SchemaDate]
    }
}​

If I don't specify any properties for the fields, the model is setup
correctly.

Thanks,

Dave

--

-- 
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm@...
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe@...
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en

David Boon | 20 May 14:52
Picon

dup key MongoError: E11000 when trying to do an upsert

I'm trying to perform an "upsert" by passing a raw json object to the constructor of a model object then invoke "save()".  The model is defined with a unique index on the "name" attribute, and the name attribute is required.  When I save a document I get the following error:
MongoError: E11000 duplicate key error index: db.users.organizations.$_id_  dup key: { : ObjectId('4fb846e3cfaa183b15000006') }

I think I'm probably using mongoose incorrectly.  Is save() supposed to figure out if the document should be updated or inserted?  Doesn't this error seem wrong?  

Is this how I should be doing an upsert?:

//assume I have some object like and it already exists in a collection
req.body = {
  '_id': '4fb846e3cfaa183b15000006'
  , 'name': 'David'
  , 'n_name': 'david'
  , 'other': 'other stuff'
};

// the utl.reject removes the '_id' and 'name' fields from the object(first arg)
var org = new Org(req.body, utl.reject(req.body, ['_id']));

org.save(function(err, m) {
  if (err) {   //error does occur here
    log.error(err.stack);
    callback(err, null);
  }
  else {
    log.debug(m + ' saved.');
    callback(null, m);
  }
});

This save call, when being invoked on an existing document throws the error below, however it works fine when creating a new document:

MongoError: E11000 duplicate key error index: db.users.organizations.$name_1  dup key: { : "a" }
        at Db.wrap (/Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1675:11)
        at [object Object].<anonymous> (/Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js:297:26)
        at [object Object].g (events.js:156:14)
        at [object Object].emit (events.js:88:20)
        at Db._callHandler (/Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1290:25)
        at /Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:329:30
        at [object Object].parseBody (/Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:118:5)
        at [object Object].<anonymous> (/Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:320:22)
        at [object Object].emit (events.js:67:17)
        at [object Object].<anonymous> (/Users/evadnoob/Projects/mtrxi/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:147:13)


I've tried removing the field name when saving, just as a test, and that obviously causes a problem in that the field 'name' is required.  I'd like to use the same "org.save" for both updates and inserts by passing raw json.  Is there a pattern for doing upsert with "save"?  I'd like to avoid doing Model.update(), since that apparently bypasses mongoose validation etc.  

Thanks, Dave

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
pardoner | 20 May 07:15
Picon

Mongoose won't output Array in nested Schema

Is there limit to how deep your objects can go in Mongoose?

[
{
  _id: 4fb073e2c11f3348c48857f3,
  name: 'Name',
  location: [
    {
      title: 'title',
      city: 'New York',
      country: 'United States',
      languages: [Object],  <<--- This should be a [String] like:
['English', 'Spanish', ...]
    }
  ]
},
{
  _id: 4fb073e2c11f3348c48857fc,
  name: 'Name',
  [...]
}
]
Not sure why the "languages" Array is outputting "[Object]" instead of
and Array of Strings. I've also notice that if I remove the "[]" and
just use a String data type in the Schema it outputs a comma delimited
list as a String

Victor Powell | 18 May 22:25
Picon
Gravatar

get the Model from the document instance?

Hey all, 


I'm writing a plugin but I'd like it to be used when the name of the model instance isn't known up front. that is, I'd like to be able to do something like this:

function myPlugin(schema,opts){
  mySchema.add({..});
  mySchema.methods.someMethod = function(){
    // I want to retrieve the Model here from the "this" document reference. 
    // maybe something like...
    var MyModel = this.__proto__.model; // doesn't work :(
    var MyModel = mongoose.model(this.__proto__.modelName); // doesn't work :(
  }
}

i know this is somewhat obscure but is this possible?

Best,
Victor

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
Petrov | 18 May 21:55

Universal statics for Schemas & using JSON.stringify for search queries

Hello all,

I have a question on how (if it's possible!) to attach a static method
to the Schema class directly, so that the same method would be
available on all models? For example, using the docs, could I do
something like

Schema.prototype.statics.search = function search (name, cb) {
  return this.where('name', new RegExp(name, 'i')).run(cb);
}

is there a way to make the 'search' method universal? So that whatever
model was initiated, the 'this' would apply to that model. Then I
could call

Animal.search('Rover', function (err) {
  if (err) ...
})

or

Alien.search('ET', function(err) {
}

and this would always produce the search Animal.where... or
Alien.where... I tried fiddling with Schema.prototype but I couldn't
get it to work.

Second question - if I do like so

var searchTerms = {};
searchTerms['name'] = 'Joe';

searchTerms = JSON.stringify(searchTerms);

Person.find(searchTerms, function(err, people) {...});

is returning all records, and not returning only docs with { 'name' :
'Joe'} ??

Much thanks!

madhums | 18 May 07:25
Picon
Gravatar

returning values from nested functions in virtuals

I have an Item schema and a User schema. Item has user as a referenced object. I want to retrieve the count of items the user owns. So I am creating a virtual like this

UserSchema
  .virtual('itemsCount')
  .get(function () {
    var count = 0
      , Item = mongoose.model('Item')

    Item.count({owner: this._id}, function (err, c) { count = c })

    return count
})

The problem I am facing here is, no matter what I do, count is always 0. I found a few questions similar to this on S.O, but there were no correct answers... I guess this is a typical async issue...

Any help appreciated...

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
Aaron Heckmann | 17 May 16:06
Picon
Gravatar

headed to jsconf.ar

I'm headed to Argentina for jsconf. Anyone else?

Stanislas Marion | 16 May 19:29
Picon
Gravatar

Should methods and statics be asynchronous or not and what are the implications?

I have defined a normalize method for a field in my Schema, so I have 

ASchema.methods.normalizeField = function () { 
  //normalize 
  return;
};

I'm wondering if it's bad that it is synchronous. More generally, what is the right way to think about these questions? I read everywhere that synchronous code blocks, and I can understand that in case of IO like reading files, streaming stuff, etc, but how about for a simple function like that? Does it block anything I'm not aware of?

Thanks a lot

--
http://mongoosejs.com
http://github.com/learnboost/mongoose
You received this message because you are subscribed to the Google
Groups "Mongoose Node.JS ORM" group.
To post to this group, send email to mongoose-orm-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
mongoose-orm+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/mongoose-orm?hl=en
Don Nguyen | 16 May 03:41
Gravatar

Why doesn't MongooseJS correctly populate my fields?

I'm trying to adapt the example here

http://mongoosejs.com/docs/populate.html

I have removed stories and am trying to add a 'friends' field
instead.  My code is as follows

var PersonSchema = new Schema({
    name    : String
  , age     : Number
  , friends : [{ type: Schema.ObjectId, ref: 'Person' }]
});

var Person = mongoose.model('Person', PersonSchema);

var aaron = new Person({ name: 'Aaron', age: 100 });
var bill = new Person({ name: 'Bill', age: 97 });

aaron.save(function (err) {
    if (err) throw err;
    bill.save(function(err) {
        if (err) throw err;
        var charlie = new Person({ name: 'Charlie', age: 97, friends:
[aaron._id, bill._id] });
        charlie.save(function(err) {
            if (err) throw err;
            Person
            .findOne({name: 'Charlie'})
            .populate('friends')
            .run(function(err, friends) {
                if (err) throw err
                console.log('JSON for friends is: ', friends);
                db.disconnect();

            });

        });

    });

});

It prints out the following text

JSON for friends is:  { name: 'Charlie',
  age: 97,
  _id: 4fb302beb7ec1f775e000003,
  stories: [],
  friends:
   [ { name: 'Aaron',
       age: 100,
       _id: 4fb302beb7ec1f775e000001,
       stories: [],
       friends: [] },
     { name: 'Bill',
       age: 97,
       _id: 4fb302beb7ec1f775e000002,
       stories: [],
       friends: [] } ] }

In other words it is printing out the 'charlie' object.  My desired
functionality is for MongooseJS to use ObjectIds in the friends field
and populate an array with the matching objects (aaron and bill).  In
other words something more along the lines of

[ { name: 'Aaron',
       age: 100,
       _id: 4fb302beb7ec1f775e000001,
       stories: [],
       friends: [] },
     { name: 'Bill',
       age: 97,
       _id: 4fb302beb7ec1f775e000002,
       stories: [],
       friends: [] } ]

What am I doing wrong?


Gmane