node.js mongoose find() 方法使用对象中的键值
node.js mongoose find() method usage with key value in object
我想使用 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 游乐场示例 here
在mongoose
中会非常相似:
Newcontract.findOne({
"contractInfo.userid": req.body.id
})
请注意,如果需要,您可以使用 findOne()
只获取一个对象。
我想使用 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 游乐场示例 here
在mongoose
中会非常相似:
Newcontract.findOne({
"contractInfo.userid": req.body.id
})
请注意,如果需要,您可以使用 findOne()
只获取一个对象。