简体   繁体   English

node.js mongoose find() 方法使用对象中的键值

[英]node.js mongoose find() method usage with key value in object

I'd like to find data from mongodb using find() function Here is my schema我想使用 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});

and what I tried is我试过的是

Newcontract.find({contractInfo: {userid: {$eq: req.body.userid}}})

But I couldn't fetch data based on this userid in contractInfo object但是我无法根据 contractInfo 对象中的这个用户 ID 获取数据

How to do it?怎么做?

Thanks谢谢

You are not querying correctly.您没有正确查询。

You need something like this:你需要这样的东西:

db.collection.find({
  "contractInfo.userid": "yourid"
})

Mongo playground example here Mongo 游乐场示例在这里

In mongoose will be very similar:mongoose中将非常相似:

Newcontract.findOne({
  "contractInfo.userid": req.body.id
})

Note that you can use findOne() to get only one object if you want.请注意,如果需要,您可以使用findOne()仅获取一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM