I can't get populate() to work on my sails.js project

有些话、适合烂在心里 提交于 2019-12-13 18:26:31

问题


I've been struggling for hours to get the simplest populate() query working on my new sails.js project. The problem is that the field to populate always has an empty array. I've pored over the examples, so I don't think I have a syntax error, but maybe my tired eyes aren't letting me see.

Here are the two models + method that's making the query:

Model Department:

    attributes: {
    id: {
        type: 'integer',
        primaryKey: true
    },
    name: {
        type: "string",
        required: true
    },
    shortName: {
        type: "string"
    },
    schoolName: {
        model: 'Schools'
    },
    courses: {
        collection: 'Courses',
        via: "departmentId"
    }
},

Model Courses:

    attributes: {
    id: {
        type: "integer",
        primaryKey: true
    },
    name: {
        type: "string",
        required: true
    },
    shortName: {
        type: "string"
    },
    departmentId: {
        model: "Departments"
    }
},

And finally, the method making the call:

    getDepartmentsBySchool: function(schoolName, callback){
    Departments.find({schoolName: schoolName}).populate("courses").exec(function(error, departments){
        if(error){
            console.log("Departments could not be found");
            return callback(error, []);
        } else{
            console.log(departments.length + " departments found");
            return callback(null, departments);
        }
    });
}

Result:

courses: []

always.

I am using MySQL, so the adapter is sails-mysql. Any sort of pointer would be greatly appreciated so that I don't have to move away from using this framework.

EDIT:

Changing the migration to "alter" results in the following:

!http://tinypic.com/r/9kv9ev/8


回答1:


I tested the code sample provided by you at my end. Instead of keeping shoolName as a reference to another collection, I had kept it as string since I wanted to test the association between departments and courses. Everything seems to work fine. Courses were getting populated perfectly. You might wanna check one thing. While using associations of the type:

   schoolName: {
        model: 'Schools'
    },

the schoolName must contain the id of record from schools table. I hope you are setting that up correctly.

Sometimes it can be an issue related to the node module sails-mysql. You may try reinstalling sails-mysql module

npm uninstall sails-mysql
npm cache clear
npm install sails-mysql

Let me know if this works or not.



来源:https://stackoverflow.com/questions/27264828/i-cant-get-populate-to-work-on-my-sails-js-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!