nodejs在MongoDB上拥有多对多的关系

时间:2022-06-01 21:10:35

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?

我一直在尝试使用mongoose populate方法,但没有成功。有没有人知道如何处理此事的任何好的教程或示例?

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.

首先,我需要以某种方式保存事件以添加用户到事件。然后通过使用populate我可以“装扮”事件数组和用户数组中的每个对象。最好在post save callback中,如果我理解正确填充。

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.

所以我知道id正确存储,但是当我运行doc.populate()时,返回的文件将events数组为空。只是不明白。

1 个解决方案

#1


1  

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

使它工作...使用mongo-relation包为我添加所需的id,但是这个插件的文档让我改变了架构形式

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

to

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

once corrected, it worked.

一旦纠正,它就有效了。

#1


1  

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

使它工作...使用mongo-relation包为我添加所需的id,但是这个插件的文档让我改变了架构形式

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

to

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

once corrected, it worked.

一旦纠正,它就有效了。