0

After populating data i get result not as expected.

Example:

//User.js Model
module.exports = {
  attributes: {
    //"id" attribute is here primary key by default

    schools: { collection: 'School', via: 'id' },
    name: { type: 'String', trim: true, required: true }
  }
}

And this is my School.js

//School.js Model
module.exports = {
  attributes: {
    //"id" attribute is here primary key by default

    name: { type: 'String', trim: true, required: true },
  }
}

My User entity data looks like this:

//User document in MongoDB
{
  _id: 1,
  name: "Foo",
  schools: [1,2,3]
}

My School entity data looks like this:

//School documents in MongoDB
{
    _id: 1,
    name: "School 1"
}
{
    _id: 2,
    name: "School 2"
}
{
    _id: 3,
    name: "School 3"
}

Now i want to populate the schools. I do it like this:

User.find().populate("schools").exec(function(err, res){ console.log(res[0]) });

And this is what i get as a result:

{
  schools: [Getter/Setter],
  name: "Foo",
  id: 1
}

Expected:

{
  schools: [
    {id: 1, name: "School 1"},
    {id: 2, name: "School 2"},
    {id: 3, name: "School 3"}
  ],
  name: "Foo",
  id: 1
}

How can i get expected results?

I use MongoDB as data storage.

Versions:

Sails.js: v0.10.0-rc5

Waterline: v0.10.0-rc7

sails-mongo: 0.10.0-rc2

Bogdan Le
  • 2,216
  • 1
  • 20
  • 21

1 Answers1

1

Those are the expected results when using console.log! If you want to see the expanded object, do:

console.log(res[0].toObject());
sgress454
  • 24,870
  • 4
  • 74
  • 92
  • Nice. Now i see strange empty array but not expected rows. Do i something wrong? – Bogdan Le Apr 02 '14 at 21:02
  • Actually, judging from the `User` document you posted, something is missing from your explanation. The `id` in Mongo should be an ObjectID, not a number, and it shouldn't have a `schools` field at all (there should be a `school_id__user_schools` collection instead). When I create an app and use the model definitions you provided, it works fine. – sgress454 Apr 02 '14 at 21:11
  • School `_id` is an integer not an ObjectID like `User` has it. I've updated my question (Added School documents). I also see that my `school_id__user_schools` collection is empty. Do i understand it right, I cannot use Integer value in `_id` to get population work? – Bogdan Le Apr 03 '14 at 17:17
  • 1
    Are you using a pre-existing Mongo DB with a new Sails project? This is fine, but you'll want to set `autoPk: false` on the `School` model, and explicitly define an `id` attribute with an `integer` type. Then it should work fine, but the embedded `schools` document in the `user` collection in your existing MongoDB is meaningless to Sails (and possibly problematic). Sails associations work via join tables (in this case `school_id__user_schools`) even for Mongo. The join table is populated when you add a `School` to a `User` instance via `myUserInstance.schools.add(schoolId)`. – sgress454 Apr 03 '14 at 18:41