简体   繁体   中英

How can I find a property of a mongoose model by another property?

I have a mongoose schema as below:

     var personnelSchema = new Schema({

        fullName: String,
        dob: String,
        cNumber: String,
        address: String,
        wCard: String,
        dLic: Number,
        hrate: Number,

});

How can i find the property "hrate" by having only "fullName". I don't have access to ID otherwise I would find it by id.

You can see the mongoDB docs on find here: https://docs.mongodb.com/manual/reference/method/db.collection.find/

On mongoose here: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html/

But finding documents by field is usually done via:

Model.findOne({ fullName: 'someName'}, function (err, doc){
  // doc is a Document
});

If you just want to hrate from fullname property then you can use projection .

Use find for fetch all record and findOne for first match record.

  var projection = 'hrate' 

  UserModel.findOne({
    fullName: "Some String"
  }, projection, function (err, data) {
    if (!data) {
      callback('No data found', null)
    } else {
      callback(err, data)
    }
})



// Query would be in MongoDB shell:

> db.getCollection('test').findOne({fullName : "Hardik Shah"}, {'hrate' : 1})

If you want full document along with hrate then don't use projection

  UserModel.findOne({
    fullName: "Some String"
  }, function (err, data) {
    if (!data) {
      callback('No data found', null)
    } else {
      callback(err, data)
    }
})



// Query would be in MongoDB shell:

> db.getCollection('test').findOne({fullName : "Hardik Shah"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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