nicholaswmin
nicholaswmin

Reputation: 22989

Mongoose return only one element from document's nested array

I'd like to fetch a single element within an array in my document, without fetching the whole array itself. Is that possible to do using Mongoose?

I've tried using dot.notation but it doesn't seem to work - It just fetches empty nested objects after the "index dot"

  // Here I'd like to get 
  // The first undo-ed item from the first board within my `boardBucket`

  Room.findOne({name: this.name}, `boardBucket.items.0.undoedItems.1`, (err, result)=> {
    if (err) throw err;
    console.log(JSON.stringify(result, null, 4));
  })

Is there any way to achieve this?

Reasons I'd like to avoid fetching the whole array

Here's my Schema in case it helps:

var roomSchema = new mongoose.Schema({
    name: String,
    boardBucket: {
      currentBoardId: String,
      items: [
        {
          boardId: String,
          boardItems: Array,
          undoedItems: Array, // <- Need to get a *single* element from this array
          viewPosition: String
        }
      ]
    }
});

Upvotes: 2

Views: 4447

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

you can use slice funtionality of query provided by mongoose. Go through mongoose documentation on slice for better understanding.

According to the documentation:

slice([path], val)

Specifies a $slice projection for an array.

Parameters:

[path] <String>
val <Number> number/range of elements to slice

Try this for your problem, i hope it works:

Room.findOne({name: this.name})
    .slice('boardBucket.items', 1)
    .slice('boardBucket.items.undoedItems', [1,1])
    .exec()

This will return the first element of the items array, and the second of undoedItems.

Upvotes: 5

Related Questions