I currently have two collections, which are Schools
and Contacts
. The Schools
collection has already been populated with thousand of data while Contacts
is a new collection which is still empty.
Now there's a schema change for both of them. Here's the schema detail:
// ----------- 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
}
}
};
And here's my code when creating a new contact:
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) });
});
However, when I check on my database, contacts
has been created but without schools
attributes. And the related schools
also still has no contacts
attribute.
I've tried the following;
newContact.schools.add([schoolId]);
// or --
newContact.schools.add(schoolObj);
// or --
newContact.schools.add([schoolObj]);
I've tried to switch the dominant
attribute between those two collections and doing the execution reversed like,
school.contacts.add(newContact);
I've also tried these solution and no lucks;
Am I missing something here? Any suggestion is appreciated..
Your code is fine, it attaches schools
to contacts
.
In sails console
, run this:
Contacts.find(contactId).populateAll().exec(console.log);
If it prints contact along with schools array populated, data is persisted in DB. It might be in a separate collection rather than being inside Contacts
in MongoDB.
PS: pipeline
definition has a typo in defaultTo
(should be defaultsTo
)