在猫鼬中填充时如何获得第一项?

How to get first item when populating in Mongoose?

我有两个如下所示的模式:

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);

它们之间是关系many-to-one。最主要的是,当我尝试从 search_query_items.find({'search_query': value}).populate('auction').exec(function(err, query) 之类的数据库获取数据时,我得到的是 query[0]['auction'][0] 而不是 query[0]['auction']。填充时是否有可能以某种方式获得第一个元素?

你可以试试这个:

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

你得到了一个数组对象,因为你定义了一个拍卖字段,它是一个拍卖数组