const dbConfig = require("../config/config.js"); const mongoose = require("mongoose"); mongoose.Promise = global.Promise; const db = {}; db.mongoose = mongoose; db.url = dbConfig.url; db.users = require("./users.model.js")(mongoose); db.listservices = require("./listservices.model.js")(mongoose); db.services = require("./services.model.js")(mongoose); db.reviewservices = require("./reviewservices.model.js")(mongoose); module.exports = db;
listservices.model.js
module.exports = mongoose => { const Listservices = mongoose.model( "listservices", mongoose.Schema( { type: String, services_name: String, image: String, active: Boolean, services: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Services' }] }, { timestamps: true } ) ); return Listservices; };
Services.model.js
```module.exports = mongoose => { // const Listservices = require('./listservices.controller'); const Services = mongoose.model( "services", mongoose.Schema( { name: String, description: String, otherdetails: String, location: String, coordinate: Array, photos: Array, service_provided: String, verified_by: Array, closed: Boolean, active: Boolean, servicescategories: { type: mongoose.Schema.Types.ObjectId, ref: 'listservices' }, reviewservices: [{ type: mongoose.Schema.Types.ObjectId, ref: 'reviewservices' }], }, { timestamps: true } ) ); return Services; };
Controller
exports.findAll = (req, res) => { const services = req.query.services; var condition = services ? { services: { $regex: new RegExp(services), $options: “i” } } : {}; Services.find(condition ).populate(‘servicescategories’)
.then(data => { res.send(data); console.log(data); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving services." }); });
};
The output is showing id, but not fetching the data from the other collection
[{“_id”:”60a27c66d87174379c93d7b5″,”name”:”MY data name”,”closed”:false,”active”:false,”listservices”:”60a2606680405c41c05cf005″,”createdAt”:”2021-05-17T14:23:34.412Z”,”updatedAt”:”2021-05-17T14:23:34.412Z”,”__v”:0}]
Thanks in advance
Advertisement
Answer
You are trying to use different name in your controller, populate receives 4 parameters- path, selection(fields to be return) , condition, options (like {limit:10}):
exports.findAll = (req, res) => { const services = req.query.services; var condition = services ? { services: { $regex: new RegExp(services), $options: "i" } } : {}; Services.find().populate({path: 'servicescategories', select: 'services_name'}) // put correct name here .then(data => { res.send(data); console.log(data); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while retrieving services." }); }); };