mikeso
mikeso

Reputation: 1

how to populate keystoneJS relationship

in keystoneJs's doc: Populating related data in queries

You can populate related data for relationship fields thanks to Mongoose's populate functionality. To populate the author and category documents when loading a Post from the example above, you would do this:

Post.model.findOne().populate('author categories').exec(function(err,post) {
    // the author is a fully populated User document
    console.log(post.author.name);
});

my question is that there is any options I can configure so these List APIs can populate the many relationship automatically.

thanks.

mike so

Upvotes: 0

Views: 1834

Answers (2)

Leopold Kristjansson
Leopold Kristjansson

Reputation: 2784

I think not. This is how I do it when I use Keystone as an API (using .populate).

exports.getStoreWithId = function (req, res) {
Store.model
    .find()
    .populate('productTags productCategories')
    .where('_id', req.params.id)
    .exec(function (err, item) {
        if (err) return res.apiError('database error', err);
        res.apiResponse({
            store: item,
        });
    });

};

Upvotes: 1

Jake Stockwin
Jake Stockwin

Reputation: 262

Pretty sure the short answer here is no. If you want to populate you'll need to include the .populate.

That being said, keystone gives you access to the mongoose schema, so the answer here should work. Obviously their mongoose.Schema is done by your Post.add stuff so I think you can ignore their first snippet, and you should be able to add the hooks as Post.schema.pre(... for the second snippet.

The Post.schema.pre('save',... hooks definitely work with keystone, so I assume the pre-find hooks work too, however I've not actually tested this. (I'd be interested to know the outcome though!)

Finally, if that works, you could also have a look at the mongoose-autopopulate package, and see if you can get that to play nicely with keystone.

Upvotes: 0

Related Questions