1

I'd like to find data from mongodb using find() function Here is my schema

  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

How to do it?

Thanks

SS-Tobi
  • 38
  • 2
  • 8
  • Minor note: it's a good practice to always use the `new` operator when constructring –  Nov 03 '20 at 16:40

1 Answers1

6

You are not querying correctly.

You need something like this:

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

Mongo playground example here

In mongoose will be very similar:

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

Note that you can use findOne() to get only one object if you want.

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Thanks, "contractInfo.userid": req.body.id I tried with it but I can not see data if I use Newcontract.find({status: "signed", a_status: req.body.a_status}) then this is finding data but if I use Newcontract.find({status: "signed", a_status: req.body.a_status, "contractInfo.userid": req.body.userid}) then no data is coming – SS-Tobi Nov 03 '20 at 15:06
  • So please, edit the question and add: Complete schema, a DB collection example and an expected output. Without knowing that is not easy find a solution. – J.F. Nov 03 '20 at 15:09
  • @SS-Tobi I've tried the query with the schema and works for me. Can you check if ```req.body.id``` is a value which exists into DB? – J.F. Nov 03 '20 at 15:21
  • yes, I was wrong with userid, it's working fine now, thanks for your help – SS-Tobi Nov 03 '20 at 15:29