Ahsan Ahmad Raheel
Ahsan Ahmad Raheel

Reputation: 303

Is there any way to populate created data in sails js (mongodb)

i have a model named Business which have a feild address with type modal: Address, i want to send the address object with business data instead of only id when the business is created.. simple create method is just return id of created address object i want to populate the response that's why i am using this:

register: function(req, res) {
        const values = req.body;
        Business.create(values).then(function(response) {
            Business.findOne({ id: response.id }).populate('address').then(function(response) {
                res.ok(response);
            });
        });
    },

But i dont think this is a proper way.. i am querying database again to populate the result. this is giving me exactly what i want. i want to use something like this:

    register: function(req, res) {
            const values = req.body;
            Business.create(values).then(function(response).populate('address') {
                 res.ok(response);
            });
        },

or anything that remove the second query to the database

i know this is crazy... but please help

The model is

module.exports = {
  schema: true,

  attributes: {
    name: {
      type: 'string'
    },

    description: {
      type: 'string'
    },

    address: {
      model: 'Address'
    },

    email: {
      type: 'email',
      unique: true
    },

    landline: {
      type: 'string'
    },

    logo: {
      model: 'Image'
    },

    status: {
      type: 'string',
      enum: ['open', 'closed'],
      defaultsTo: 'open'
    },

    uniqueBusinessName: {
      type: 'string',
      unique: true
    },
  },
};

Upvotes: 2

Views: 518

Answers (1)

sgress454
sgress454

Reputation: 24948

The create class method does not support populate, so the way you're doing this is correct. If you'd like to propose this as a feature, please check out the Sails.js project's guidelines for proposing features and enhancements!

Upvotes: 2

Related Questions