简体   繁体   English

如何通过另一个属性找到猫鼬模型的属性?

[英]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". 我如何仅拥有“ fullName”来找到属性“ hrate”。 I don't have access to ID otherwise I would find it by id. 我无权访问ID,否则我会通过ID找到它。

You can see the mongoDB docs on find here: https://docs.mongodb.com/manual/reference/method/db.collection.find/ 您可以在以下位置find mongoDB文档: https ://docs.mongodb.com/manual/reference/method/db.collection.find/

On mongoose here: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html/ 关于此处的猫鼬: 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 . 如果只想从fullname属性中hrate ,则可以使用projection

Use find for fetch all record and findOne for first match record. 使用find来获取所有记录,并使用findOne来获取第一个匹配记录。

  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 如果您想要完整的文档以及hrate请不要使用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"})

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

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