node.js - node.js mongoose find() 方法使用对象中的键值
问题描述
我想使用 find() 函数从 mongodb 中查找数据这是我的架构
const newcontractSchema = mongoose.Schema({
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false,
index: true,
},
status: {type: String, required: false, default: 'init'},
a_status: {type: String, required: false, default: 'pending'},
contractInfo: {
startDate: {type: Date},
endDate: {type: Date},
expectedUsage: {type: Number, default: 2000},
provider: {type: Object},
rate: {type: Number},
term: {type: Number},
userid: {type: String}
}, {timestamps: true});
我尝试的是
Newcontract.find({contractInfo: {userid: {$eq: req.body.userid}}})
但是我无法根据 contractInfo 对象中的这个用户 ID 获取数据
怎么做?
谢谢
解决方案
您没有正确查询。
你需要这样的东西:
db.collection.find({
"contractInfo.userid": "yourid"
})
Mongo游乐场示例在这里
在mongoose
将非常相似:
Newcontract.findOne({
"contractInfo.userid": req.body.id
})
请注意,如果需要,您可以使用findOne()
仅获取一个对象。
推荐阅读
- php - php脚本在使用cronjob时不使用phpmailer发送邮件,但在直接访问脚本时发送邮件
- visual-studio - 如何为 MFC 对话框按钮添加渐变色?
- typescript - 当我更改 dxGrid 查找数据源时,查找停止扩展
- ios - macOS - 有没有办法知道哪个文本字段触发了 performKeyEquivalent?
- python - 无法使用 python selenium 启动浏览器
- angular - 单击后如何禁用按钮并且它只单击一次?
- php - 判断PHP流是否支持搜索
- javascript - 获取两个组件中的元素
- javascript - 如何在循环中执行异步代码?
- python - 如何使用来自 2 个列表的 python 列表理解创建字典