我目前有两个集合,分别是Schools
和Contacts
。 Schools
集合已填充了数千条数据,而 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);
我也尝试过这些解决方案,但没有成功;
- http://sailsjs.com/documentation/concepts/models-and-orm/associations/many-to-many
- https://github.com/balderdashy/waterline-docs/issues/20
- Sails.js How to insert data into a join table (Many to Many)
我在这里遗漏了什么吗?任何建议表示赞赏..
最佳答案
您的代码很好,它将学校
附加到联系人
。
在 sails 控制台
中,运行以下命令:
Contacts.find(contactId).populateAll().exec(console.log);
如果它打印联系人以及填充的学校数组,则数据将保留在数据库中。它可能位于单独的集合中,而不是位于 MongoDB 中的Contacts
内。
PS:pipeline
定义在 defaultTo
中存在拼写错误(应为 defaultsTo
)
关于node.js - Sails 将数据创建为多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713306/