Get attribute inside an array in Mongodb

Asked

Viewed 881 times

0

Hello, friends. Good evening! I’m having a problem developing an api, I need to query some attributes within an array of a Schema in Mongodb to add them to an email for an order.

Could someone help me? Below is the model of Schema:

I need to take the values of the items array, but 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'
        }
    }],
});

  • You’ve already taken a look at this recourse for Query in arrays?

  • What is the question more specifically? What have you tried?

1 answer

1

You want to apply a filter that only picks up these three fields within the right items. The findOne(conditions, [fields], [options], [callback]) or without callback with async/await. 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])
    }
})

Variable result result with a list inside the object:

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

In the first result I used unstructuring to pick up only items, in the second result with callback it gets more complicated but nothing that makes it too difficult.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.