1

I have a little question. I have a User schema which contains a table fields redirecting to the Table schema. A Table element can contain a name, I want this name to be unique per User but not between User.

Example: User1 -> Table1.name: "foo" User2 -> Table1.name: "foo"

But this User1 -> Table2.name: "foo" cannot be possible.

This is the User Schema:

var UserSchema = new mongoose.Schema({
    username: {  type: String, required: true, index: {  
    unique: true } },
    email: {  type: String, required: true, index: {unique: true } },
    password: {  type: String, required: true },
    tables: [{ type: Schema.Types.ObjectId, ref: 'Table' }],
    resetPasswordToken: String,
    resetPasswordExpires: Date,
    uuid: String,                
});

This is the Table schema:

var TableSchema = Schema({
    name: { type: String, required: true, index: { unique: true }},
    logos: [{ type: Schema.Types.ObjectId, ref: 'Logo'}],
});

And this is where I do the queries:

app.post('/newTab', function(req, res){

    var use = req.user.username;
    var newTab = new Table({
        name: req.body.name,
    });

    newTab.save(function(err, docs){
        if (err) 
        {
            console.error(err);
            res.writeHead(500);
            res.end();
        }
        else
        {
            User.findOne({username: req.user.username}, function(err,  docs) {
                if(err)  {throw (err);}
                else
                {
                    docs.tables.push(newTab);
                    docs.save(function(err, docs){
                        if (err) return console.error(err);
                        res.writeHead(200);
                        res.end(userId);
                    });
                }
            }); 
        }
    });

For now, I cannot add the same table name for two different User .. I also tried something with sparse index but can't figure how it works

Naguib 凪
  • 25
  • 6
  • In the above you only have one distinct user with the username `req.user.username`, where is the other user to add the table to? – chridam Jun 15 '16 at 06:40
  • req.user.username contains the logged in user thanks to PassportJS – Naguib 凪 Jun 15 '16 at 06:42
  • Yes, but in your question you are saying "I cannot add the same table name for two different User", my question is, where is the other user you are referring here to? – chridam Jun 15 '16 at 06:46
  • on my DB, when I logout and login with an other user, I cannot add a table which have the same name as the table of the previous user – Naguib 凪 Jun 15 '16 at 06:52

0 Answers0