Carlo S
Carlo S

Reputation: 983

Mongo: query on subdocs

Hello I have this problem when checking if a subdocument exist before pushing a new subdocument.

var UserSchema = new Schema({
   name        : String,
   app_key     : String,
   app_secret  : String,
   tasks       : [{type: Schema.ObjectId, ref: 'Task'}] // assuming you name your model Task 
});

var TaskSchema = new Schema({
   name            : String,
   lastPerformed   : Date,
   folder          : String,
   user            : {type: Schema.ObjectId, ref: 'User'} // assuming you name your model User
});

With this, your query for all users, including arrays of their tasks might be:

User.findOne({...}).populate('tasks').run(function(err, user) {
    var subdoc = user.tasks.id(mytask.id);
    if(subdoc){
        //not exist
        //push
    }
});

This is the error:

TypeError: Object  has no method 'id'

Upvotes: 1

Views: 133

Answers (1)

sfritter
sfritter

Reputation: 891

You are getting that error because there is no 'id' field defined for the 'tasks' subdocument. You might have meant 'user.tasks._id', which will return the ObjectId that MongoDB adds to its documents by default.

Upvotes: 1

Related Questions