简体   繁体   中英

Query mongodb documents in loopback

Im trying to query children documents but it throws following error.

Error: Cannot call Project.find(). The find method has not been setup. The PersistedModel has not been correctly attached to a DataSource!

I can see only project documents in explorer, i want to see its children sub documents users too.

project.json

 { "name": "Project", "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "properties": { "name": { "type": "string", "required": true }, "description": { "type": "string", "required": true } }, "validations": [], "relations": { "user": { "type": "belongsTo", "model": "User", "foreignKey": "userId" } }, "acls": [], "methods": {} } 

project.js

 'use strict'; module.exports = function(Project) { Project.find().then((projects => console.log(projects))).catch((err) => console.log(err)); }; 

Try changing your code to be:

'use strict';

module.exports = function(Project) {


Project.find().exec().then((projects => console.log(projects))).catch((err) => 
console.log(err));
};

I added .exec() to the query.

The Model.js file is not really for executing things (though it's possible if you use events ).
The server has not been started up yet, datasources haven't been connected to models yet. The only information which you have access to and can customize are the properties of that one model.

If you want do things on startup put the script in the server/boot directory.

server/boot/project.js

 module.exports = (server) => {

      const Project = server.models.Project;
      Project.find().then((projects => console.log(projects))).catch((err) => console.log(err))
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM