如何从mongoose模式中的数组中select一个值

使用MongoDb版本3.2.7

我有一个这样的mongoose模式,它有一个分支模式中的股票数组。 我想select股票数组中的一个subCategoryId ,并获得该subCategoryId currentPrice只,因为我正在查询

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

此查询适用于更新值的时间,因为我可以完美地更新所选子subCategoryIdcurrentPrice 。 但是,当我想要得到一个特定的subCategoryId的价格下面的查询得到我在分支集合中的所有股票。 我正在使用的查询是这样的:

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

mongoose纲要

 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 } }); 

要只检索匹配的数组元素,试试这个:

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

stock.$将帮助您只从数组中检索匹配的元素。