Did a query Product.findOne({'variation.sku': req.params.productVariationSKU },{'_id': 0, 'variation.price' :1})
to find the price of a product variation.
But result returned price of all product variations. Need help to find where went wrong!
Below is product schema:
var ProductSchema = new Schema({ productId: { type: Number, required: [true, 'Product ID is required'], unique: true }, sku: String, category: [String], language: { type: String, lowercase: true, maxlength: 2, required: [true, 'Language code required'], index: true, unique: true }, name: { type: String, required: [true, 'Product name is required'] }, descLong: String, descShort: String, mainImageURL: String, galleryImageURL: [String], variation: [{ sku: String, option: [{ label: String, value: String, }], inventory: [{ name: String, quantity: Number, country: String }], inStock: Boolean, price: mongoose.Types.Decimal128 }], attribute: [{ label: String, value: [String] }], inStock: Boolean, currencySymbol: String, slug: String, metaTitle: String, metaDescription: String, relatedAccessory: [Number], htmlContentBefore: String, htmlContentAfter: String });
Below is product object from Postman:
{ "category": [], "galleryImageURL": [ "TEST.png" ], "relatedAccessory": [], "_id": "5feae4418d686300176dfbbd", "productId": 1, "language": "en", "name": "TEST PRODUCT", "descLong": "<p><strong>This is a long description</strong></p>", "descShort": "Short Description", "mainImageURL": "TEST.png", "variation": [ { "option": [ { "_id": "5feae4418d686300176dfbbf", "label": "Color", "value": "Black" } ], "inventory": [], "_id": "5feae4418d686300176dfbbe", "sku": "P-1", "inStock": true, "price": "45" }, { "option": [ { "_id": "5feae4418d686300176dfbc1", "label": "Color", "value": "White" } ], "inventory": [], "_id": "5feae4418d686300176dfbc0", "sku": "P-2", "inStock": true, "price": "45" } ], "attribute": [ { "value": [ "Black", "White" ], "_id": "5feae4418d686300176dfbc2", "label": "Color" } ], "currencySymbol": "£", "slug": "test", "metaTitle": "testmeta", "metaDescription": "This is meta description", "__v": 0 }
Below is API function:
app.get('/API/Product/GetProductVariationPrice/:productVariationSKU', async(req, res) => { try{ res.send(await Product.findOne({'variation.sku': req.params.productVariationSKU },{'_id': 0, variation :1})); } catch (err) { res.status(500).send(err); } });
Returned result from Postman:
{ "variation": [ { "price": "45" }, { "price": "45" } ] }
Question: How can I get just "45" of variation SKU "P-1"? As the result currently returns the price of variation 'P-2' as well which is not wanted. SKU should be based on the param passed to the API.
https://stackoverflow.com/questions/65802316/how-to-query-nested-document-and-return-string-result January 20, 2021 at 10:34AM
没有评论:
发表评论