如何编写MongoDb Mongoose查询以匹配两个属性
我的股票模型文件如下所示:如何编写MongoDb Mongoose查询以匹配两个属性,mongodb,mongoose,mongodb-query,mongoose-schema,Mongodb,Mongoose,Mongodb Query,Mongoose Schema,我的股票模型文件如下所示: const Stock = new Schema( { ClientId : {type : Schema.ObjectId}, ClientName : {type : String}, StockName : { type : String }, StockType : { type : String }, ConsumedQuantity : {type : N
const Stock = new Schema(
{
ClientId : {type : Schema.ObjectId},
ClientName : {type : String},
StockName : { type : String },
StockType : { type : String },
ConsumedQuantity : {type : Number},
TotalQuantity : {type : Number},
WastageQuantity : {type : Number},
},
{ timestamps: true },
);
这里还有我的库存管理员的查询:
Stock.findOne({ ClientId : clientId }, (err, stock) => {
if (err) {
return res.status(404).json({
err,
message: 'Stock not found!',
})
}
if( stock.ConsumedQuantity === undefined)
stock.ConsumedQuantity = materialConsumed
else
stock.ConsumedQuantity += materialConsumed
if( stock.WastageQuantity === undefined)
stock.WastageQuantity = materialWasted
else
stock.WastageQuantity += materialWasted
stock
.save()
.then(() => {
return res.status(200).json({
success: true,
message: 'Material in inventory has been updated!',
})
})
.catch(error => {
return res.status(404).json({
error,
message: 'Material in inventory was not updated!',
})
})
})
我希望能够基于两个条件查询我的库存项目,第一个条件是ClientId等于ClientId,这是我从服务器请求中获得的值。其次,我希望stockItem的名称与字符串匹配。我该怎么做呢?是否有AND运算符可用于在同一查询中执行ClientId:ClientId和StockName:StockName?请帮忙!多谢各位 简单地在where子句中添加第二个属性,使用AND运算符,如果需要or运算符,则使用以下语法{$or:[{region:“NA”},{sector:“Some sector”}]}
Stock.findOne({ ClientId : clientId, StockName : yourString }, (err, stock) => {
if (err) {
return res.status(404).json({
err,
message: 'Stock not found!',
})
}
if( stock.ConsumedQuantity === undefined)
stock.ConsumedQuantity = materialConsumed
else
stock.ConsumedQuantity += materialConsumed
if( stock.WastageQuantity === undefined)
stock.WastageQuantity = materialWasted
else
stock.WastageQuantity += materialWasted
stock
.save()
.then(() => {
return res.status(200).json({
success: true,
message: 'Material in inventory has been updated!',
})
})
.catch(error => {
return res.status(404).json({
error,
message: 'Material in inventory was not updated!',
})
})
})