Question

I'm trying to make a many-to-many relation between two documents in mongoose. Just can't make it work.

I've been trying to utilize the mongoose populate method, but with no success. Does anyone know any good tutorials or example on how to take on the matter?

Update:

Got schemas

var EventSchema = new Schema({
    users: [{
      type: Schema.Types.ObjectId,
      ref: 'User'
    }]
});

and

var UserSchema = new Schema({
    events: [{
      type: Schema.Types.ObjectId,
      ref: 'Event'
    }]
});

In my tests I pused to event model user like so

    event.users.push(user);
    event.save(function(err, doc) {
      user.events[0].should.equal(event._id);
      done();
    });

firstly I need to push somehow saved event to added user to event. Then by using populate I should can 'dress up' every object in events array and users array. Preferably in post save callback, if I understood populate correctly.

This test pases

  it('creates', function(done) {
    event.users.append(user);
    event.save(function(err, ev) {
      user.save(function(err, doc) {
        doc.events[0].should.equal(ev._id);
        doc.populate('events', function(err, d) {
          console.log(d);
          done();
        });
      });
    });
  });

So I know the ids are stored correctly, but when I run doc.populate() the returned document has events array empty. Just don't get it.

Was it helpful?

Solution

Made it work... used mongo-relation package to add the needed ids for me, but docs for this plugin made me change the schema form

var UserSchema = new Schema({
  events: [{
    type: Schema.ObjectId,
    ref: 'Event'
  }]
});

to

var UserSchema = new Schema({
  events: [Schema.ObjectId]
});

once corrected, it worked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top