Validating Through Relationships

39 views
Skip to first unread message

nich...@originalmachine.com

unread,
Feb 16, 2014, 5:26:30 PM2/16/14
to mongoo...@googlegroups.com
In my application, a User has many Posts. I've setup the relation, to I can populate the User's Posts or get the User's information from a Post - but one question remains:

How can I ensure that the User doesn't create the same Post twice? For instance, the Post's title needs to be unique. But it shouldn't be globally unique, just unique to that User.

Any tips on how to implement this?

Jason Crawford

unread,
Feb 16, 2014, 5:36:28 PM2/16/14
to mongoo...@googlegroups.com
Mongoose has a whole validation subsystem, and you can write arbitrary validation functions:


Hope that helps,
Jason



--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Nicholas Young

unread,
Feb 16, 2014, 9:00:56 PM2/16/14
to mongoo...@googlegroups.com, mongoo...@googlegroups.com
Yeah, I'm familiar with the custom validation functions that Mongoose provides. I was just wondering if anyone had tips on implementing the validation case I described and could guide me with best practices. 

Sent from my iPad
You received this message because you are subscribed to a topic in the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mongoose-orm/7KMgKJq6zW8/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mongoose-orm...@googlegroups.com.

Joe Wagner

unread,
Feb 16, 2014, 11:47:55 PM2/16/14
to mongoo...@googlegroups.com
You could potentially use a unique compound index.  Depending on what your schemas look like, you could do something like this:
var userSchema = {
   
...
};

var postSchema = {

    user
: {type: mongoose.Schema.ObjectId, ref: 'User'},
    title: String,
   
...
};

postSchema.index({user: 1, title: 1}, {unique: true});

Reply all
Reply to author
Forward
0 new messages