These are chat archives for Automattic/mongoose

2nd
Feb 2016
antonioaltamura
@antonioaltamura
Feb 02 2016 11:56
guys in two words I'm trying to accomplish a FindOrAdd() function: if the document i'm searching for isn't present, add a new document. I'm really struggling with this syncronous function, any tips about that? How can accomplish this simple idea?
Konstantin Baierer
@kba
Feb 02 2016 13:14
do a find() and in the callback check whether found. If not add().
Synchronous and nodejs don't play nice together most of the time. Why NodeJS if you need sync?
antonioaltamura
@antonioaltamura
Feb 02 2016 13:44
could you provide me an example, please? I choose node.js because I thought it comes easily to build a RESTful api with express. I'm not so sure, but it's late now..
Sebastien Vaucouleur
@vaucouleur
Feb 02 2016 13:53
@alfredopacino asynchronous programming in nodejs usually works as follow: f(1,2,3,what_to_do_next);
@alfredopacino 1, 2, 3 are the arguments for f, what_to_do_next is a function that will be called with the results of f
Denis Trofimov
@denistrofimov
Feb 02 2016 13:55
@alfredopacino take a look at nibirujs at http://denistrofimov.github.io/nibiru
noyg
@noyg
Feb 02 2016 14:42
Hi all, got a really annoying problem here :|
var ContactSchema = new Schema({
    name: String,
    role: String,
    phone: String,
    email: String,
    primary: Boolean
});

var ClientSchema = new Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    comments: {
        type: String,
        trim: true
    },
    creator: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    contacts: [ContactSchema],
    address: String,
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});
For some odd reason, when saving Client, the contacts don't get an ID
when I use this structure:
var ClientSchema = new Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    comments: {
        type: String,
        trim: true
    },
    creator: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    contacts: [{
        name: String,
        role: String,
        phone: String,
        email: String,
        primary: Boolean
    }],
    address: String,
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});
Contacts get an ID and everything's peachy
Any ideas?
J
@jhyland87
Feb 02 2016 14:56
Does anyone know how to suppress/catch the Unhandled rejection ValidationError: Field validation failed error? (Im expecting the error, just testing a function that I need to return a promise from, not throw an error)
Using Bluebird promises btw

Its being thrown from a static method within the model:

    fieldSchema.statics.testValidate = function( field ) {
        return new Promise( ( res, rej ) => {
            const fld = new this( field )

            fld.validate( err => {
                if ( err ) return rej( 'BBBBB' )

                res( 'SUCCESS' )
            } )
        })
    }

And called here:

Field.testValidate( fieldData )
    .then(data => {
        console.log('OK!', data)
    })
    .catch( err => {
        console.error('FAILED:',err)
    })
    .finally(() => Mongoose.connection.close())
I can tell I get to the promise rejection, but the catch doesnt actually catch it
J
@jhyland87
Feb 02 2016 16:01
@noyg did you figure that out?
Your question, with the Index
noyg
@noyg
Feb 02 2016 16:04
@jhyland87 Nope, not yet
J
@jhyland87
Feb 02 2016 16:05
Hm, seems like an interesting one. Its obviously not in the code you posted.. Wonder if it a config in the db or a default setting in mongoose
noyg
@noyg
Feb 02 2016 16:05
I'd appreciate any lead
I'm banging my head at this for the past day
J
@jhyland87
Feb 02 2016 16:06
The contacts dont get an ID, but do the clients?
@noyg try adding { _id: true }
var ContactSchema = new Schema({
    name: String,
    role: String,
    phone: String,
    email: String,
    primary: Boolean
},{ _id: true });
noyg
@noyg
Feb 02 2016 16:08
@jhyland87 tried that already
it's completely ignored
J
@jhyland87
Feb 02 2016 16:08
Wow, thats really fcking weird
noyg
@noyg
Feb 02 2016 16:08
the clients do get an _id
J
@jhyland87
Feb 02 2016 16:08
The contacts dont
let me set it up for a container in my mongolab db
and btw, im no pro, im actually new to nosql, lol
noyg
@noyg
Feb 02 2016 16:14
any new set of eyes comes with new insights
hm
noyg
@noyg
Feb 02 2016 16:17
Yup :blush:
J
@jhyland87
Feb 02 2016 16:18
Hm, so I get the ID, which I expected.. you dont..
what version mongoose?
is your db local?
noyg
@noyg
Feb 02 2016 16:18
@jhyland87 That's interesting. So no I really have no idea what I'm missing
local, yes
version - sec
J
@jhyland87
Feb 02 2016 16:18
im on 4.3.7
noyg
@noyg
Feb 02 2016 16:19
4.1.3
J
@jhyland87
Feb 02 2016 16:19
@noyg what I would recommend, is sign up on mongolab.com, for a free db, then create a collection and see if it adds the_id
that will rule out some things
would say its almost definitely the code, somewhere
(If its not there)
if it IS there, id say that points to the DB, somehow
noyg
@noyg
Feb 02 2016 16:21
umm
so, connecting from my dev machine to the remote host?
This is what you mean?
J
@jhyland87
Feb 02 2016 16:29
Yeah @noyg
Its free, super quick, easy
noyg
@noyg
Feb 02 2016 16:30
Means I have to re-set my entire app's metadata ^_^
J
@jhyland87
Feb 02 2016 16:31
Oh..
I just meant execute a quick function, lol
noyg
@noyg
Feb 02 2016 16:31
I'm quite certain it's not a local db issue
J
@jhyland87
Feb 02 2016 16:31
Maybe use the same connection string, but thats it
Eh, ok, then dont do it
Well, I have no idea :( Sorry
Do other sub-schema get the _ids?
Konstantin Baierer
@kba
Feb 02 2016 16:35
@jhyland87 About promises/validation: Did you see Automattic/mongoose#3669 Might be related, though no idea about promises myself.
J
@jhyland87
Feb 02 2016 16:35
@kba Yeah, didnt work, :-\
noyg
@noyg
Feb 02 2016 16:36
@jhyland87 yes, but none are referenced, I use only embedded sub-schemas
Konstantin Baierer
@kba
Feb 02 2016 16:37
@jhyland87 ah too bad. promises are tricky to track. elegant but confusing to debug imho.
J
@jhyland87
Feb 02 2016 16:37
Yes indeed
Created a SO question, so im sure ill get an answer there
Konstantin Baierer
@kba
Feb 02 2016 16:52
@noyg How do you create the Client model?
noyg
@noyg
Feb 02 2016 17:14
@kba mongoose.model('Client', ClientSchema);
is that what you mean?
no special effects...
J
@jhyland87
Feb 02 2016 17:15
Wheres the documentation for the available options when running queries? "Options" as in all the <options> shown here (such as A.where().findOneAndRemove(conditions, options, callback)), I dont see them on the query documentation page
I just searched by going to different pages and ctrl+f options, so maybe I missed em
Konstantin Baierer
@kba
Feb 02 2016 17:16
@jhyland87 The same as MongoDB?
J
@jhyland87
Feb 02 2016 17:16
Oh ok, lol
Again, ive only been useing MongoDB/Mongoose for like.. weeks now, heh
Konstantin Baierer
@kba
Feb 02 2016 17:17
No prob, these probs at least are easy to solve ;)
J
@jhyland87
Feb 02 2016 17:17
haha, true
Im not much of a developer, im more of an linux engineer really
@kba are the options query options? or something else, Dont see much here
The only queries ive ran so var via the cli is collection.{find,remove}( / ... / ).pretty()
Konstantin Baierer
@kba
Feb 02 2016 17:24
Oh, so you mean the options of findOneAndRemove? As in http://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove -> "Available options"?
J
@jhyland87
Feb 02 2016 17:26
Any of the [options]
there all over, lol
A.where().findOneAndRemove(conditions, options, callback) // executes
A.where().findOneAndRemove(conditions, options)  // return Query
A.where().findOneAndRemove(conditions, callback) // executes
A.where().findOneAndRemove(conditions) // returns Query
A.where().findOneAndRemove(callback)   // executes
A.where().findOneAndRemove()           // returns Query
for example, those options
Im trying to find the best way to throw an error if the documents werent found to delete, wondering if theres an option to do that
(Thats why I was looking initially @kba )
Konstantin Baierer
@kba
Feb 02 2016 17:36
Won't remove(conditions) return a callback with the number of removed documents as the second param?
In any case, why not do a find() first, message error if none are found (callback or promise) and do the delete otherwise?
noyg
@noyg
Feb 02 2016 17:38
Another odd lead!
When I move the schema to the same file, it works as expected
when I require it using ContactSchema = require('./contact'), it doesn't
Konstantin Baierer
@kba
Feb 02 2016 17:39
@noyg Ah, I see. You must make sure to reuse the same connection when setting up the model.
No wait :blush:
noyg
@noyg
Feb 02 2016 17:39
Well, then how does it work?
I mean, it should have thrown an error or something
all constraints work and everything
just the id isn't
Konstantin Baierer
@kba
Feb 02 2016 17:40
No question, it's weird behavior. I'm no expert either but I remember running into problems when using the default connection.
because the mongoose you require in one module is not the same as the mongoose in another.
Sry for being so vague here. I don't think that it will matter whether you import a Schema but try to create all the models in one place and see if that fixes it.
check this out
Konstantin Baierer
@kba
Feb 02 2016 17:49
Argh!
So ContactSchema was undefined all along.
noyg
@noyg
Feb 02 2016 17:50
can't be, since everything worked
Konstantin Baierer
@kba
Feb 02 2016 17:50
In client.js:
    contacts: [ContactSchema],
noyg
@noyg
Feb 02 2016 17:51
yup
Konstantin Baierer
@kba
Feb 02 2016 17:51
Ah, well gotta go anyway, glad it works for you @noyg
noyg
@noyg
Feb 02 2016 17:51
Yup. Thanks for everything! :)