gpt4 book ai didi

node.js - 如何从 Mongoose 模式的数组中选择一个值

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:01 25 4
gpt4 key购买 nike

使用 MongoDb 版本 3.2.7

我有一个像这样的 Mongoose 模式,它在分支模式中有一系列库存。我想在库存数组中选择一个 subCategoryId 并仅获取该 subCategoryIdcurrentPrice,因为我正在使用查询

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.$ 将帮助您从数组中仅检索匹配的元素。

关于node.js - 如何从 Mongoose 模式的数组中选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38987223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com