Kin
Kin

Reputation: 4596

How to get first item when populating in Mongoose?

I have two schemas which looks like this:

var SearchQueryItemsSchema = new mongoose.Schema({
    //...
    'auction': [{'type': mongoose.Schema.Types.ObjectId, 'ref': 'auctions'}],
    // ...
});

module.exports = mongoose.model('search_query_items', SearchQueryItemsSchema);


var AuctionsSchema = new mongoose.Schema({
    'id': mongoose.Schema.ObjectId,
    // ...
});

module.exports = mongoose.model('auctions', AuctionsSchema);

Between them are relation many-to-one. The main thing is that when i try to get data from db like search_query_items.find({'search_query': value}).populate('auction').exec(function(err, query) i get query[0]['auction'][0] instead of query[0]['auction']. Is it somehow possible to get first element when populating?

Upvotes: 0

Views: 909

Answers (1)

Phi Nguyen
Phi Nguyen

Reputation: 3056

You can try this:

var SearchQueryItemsSchema = new mongoose.Schema({
//...
'auction': {'type': mongoose.Schema.Types.ObjectId, 'ref': 'auctions'}, // remove the square backet
// ...
});

You got an array object because you defined auction field which is an array of Auctions

Upvotes: 2

Related Questions