Shumi Gupta Shumi Gupta - 3 months ago 20
Node.js Question

How to select a value from an array in mongoose schema

Using MongoDb version 3.2.7

I have a mongoose schema like this which has an array of stock in branch schema. I want to select a

subCategoryId
in stock array and get the
currentPrice
of that
subCategoryId
only, for that I am using query

var getCriteria = { "stock.subCategoryId": subCategoryId }
var update = { "stock.$.currentPrice": currentPrice }


This query works for me at the time of updating the value as I am able to update the
currentPrice
of selected
subCategoryId
perfectly. But when I want to get a price of particular
subCategoryId
the following query gets me all the stocks in the branch collection. The query I am using is this:

var getCriteria ={ "stock.subCategoryId": subCategoryId }


Mongoose Schema

var branch = new Schema({
branchName: { type: String, trim: true, index: true, default: null },
isBlocked: { type: Boolean, default: false, required: true },
email: { type: String, trim: true, required: true, unique: true, index: true },
password: { type: String, required:true },
accessToken: { type: String, trim: true, index: true, unique: true, sparse: true },
stock: [stock],
});

var stock = new Schema({
categoryId: { type:Schema.ObjectId, ref: "categoies", default: null },
subCategoryId: { type:Schema.ObjectId, ref: "subCategories", default: null },
currentPrice: { type: Number },
isBlocked: { type: Boolean, default: false, required: true },
Date: { type: Date, default: Date.now, required: true }
});

Answer

To retrieve only the matching array element try this:

branch.find(getCriteria,{'stock.$' : 1},function(err,branch){...});

stock.$ will help you to retrieve only the matched element from the array.

Comments