Get attribute within an array in MongoDB

0

Hello, friends. Good night! I'm having a problem in developing an api, I need to query some attributes within an array of a Schema in MongoDB to add them to an email in a request.

Can anyone help me? follows the Schema model below:

I need to get the values from the array 'items', however I only need price, quantity and title.

const schema = new Schema({
    customer: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Customer'
    },
    email: {
        type: mongoose.Schema.Types.ObjectId,
        required: false,
        ref: 'Customer'
    },
    name: {
        type: mongoose.Schema.Types.ObjectId,
        required: false,
        ref: 'Customer'
    },
    number: {
        type: String,
        required: false
    },
    createDate: {
        type: Date,
        required: true,
        default: Date.now
    },
    status: {
        type: String,
        required: true,
        enum: ['created', 'done'],
        default: 'created'
    },
    items: [{
        quantity: {
            type: Number,
            required: true
        },
        price: {
            type: Number,
            required: true
        },
        product: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        },        
        title: {
            type: mongoose.Schema.Types.String,
            ref: 'Product'
        }
    }],
});
    
asked by anonymous 31.07.2018 / 02:46

1 answer

1

You want to apply a filter that takes only those three fields within certain items. The findOne(conditions, [fields], [options], [callback]) or without callback with async/await . It would look like this.

  

With async / await:

const { items } = await Products.findOne({_id: 'objectId' },'items.price items.quantity items.title')
consolelog(items[0])
res.status(200).send(items[0])

Search result with async:

{
    "quantity": "",
    "price": "",
    "title": ""
}
  

No async and callback:

Products.findOne({_id: 'objectId'},'items.price items.quantity items.title', (err, result) => {
    if(err){
        console.log(err)
    }else{
        console.log(result.items[0])
        res.status(200).send(result.items[0])
    }
})

Result of variable result with a list inside the object:

{
    "quantity": "",
    "price": "",
    "title": ""
}

In the first result I used de-structuring to get only items, the second result with callback gets more complicated but nothing that makes it very difficult.

    
31.07.2018 / 09:08