Sails 将数据创建为多对多关系

Sails creating data into many to many relationship

我目前有两个合集,分别是SchoolsContactsSchools 集合已经填充了数千条数据,而 Contacts 是一个新集合,它仍然是空的。

现在他们两个的架构都发生了变化。这是架构详细信息:

// ----------- Schools.js
module.exports = {
  attributes: {
    user: {
      model: 'users'
      // Của User đã tạo
    },

    essential: {
      type: 'string'
      // Lưu toàn bộ thông tin của essential
    },

    contacts: {
      collection: 'contacts',
      via: 'schools'
    },

    pipeline: {
        type: 'string',
        defaultTo: ""
    },

    status: {
      type: 'integer',
      defaultsTo: 1
      // 0: un-active, 1: active
    }
  }
};

// ----------- Contacts.js

module.exports = {
    attributes: {
        title: {
            type: 'string'
        },

        firstName: {
            type: 'string'
        },

        lastName: {
            type: 'string'
        },

        email: {
            type: 'string'
        },

        position: {
            type: 'string'
        },

        landlinePhone: {
            type: 'string'
        },

        mobilePhone: {
            type: 'string'
        },

        externalCompany: {
            type: 'string'
        },

        schools : {
            collection: 'schools',
            via: 'contacts',
            dominant: true
        },

        user: {
            model: 'users'
        },

        activities: {
            collection: 'activities',
            via: 'contact'
        },

        status: {
            type: 'integer',
            defaultsTo: 1
            // 0: remove, 1: active, 2: unactive
        }
    }
};

这是我创建新联系人时的代码:

Contacts.create(contactData).exec(function (e1, newContact) {
    if (e1) {
      console.log("e1 ::: ", e1);
    };

    // newContact is filled with contact new data..
    console.log("Contact data has been created", newContact, schoolId);

    // Adding schools to newContact (schoolId has a value here);
    newContact.schools.add(schoolId);

    // Save
    newContact.save(function (err) { console.log('err', err) });
});

然而,当我检查我的数据库时,contacts 已经创建但没有 schools 属性。而相关的 schools 也仍然没有 contacts 属性。

我尝试了以下方法;

newContact.schools.add([schoolId]);
// or --
newContact.schools.add(schoolObj);
// or --
newContact.schools.add([schoolObj]);

我尝试在这两个集合之间切换 dominant 属性,并反向执行,例如,

school.contacts.add(newContact);

我也尝试过这些解决方案,但没有成功;

我是不是漏掉了什么?任何建议表示赞赏..

您的代码没问题,它将 schools 附加到 contacts

sails console、运行这个:

Contacts.find(contactId).populateAll().exec(console.log);

如果它打印联系人以及填充的学校数组,则数据将保留在数据库中。它可能在一个单独的集合中,而不是在 MongoDB.

中的 Contacts

PS: pipeline定义在defaultTo中有错别字(应该是defaultsTo