mongoose find a document by reference property

后端 未结 1 872
耶瑟儿~
耶瑟儿~ 2021-02-03 10:08

I have a first model Person:

var personSchema    = new Schema({
    firstname: String,
    name: String
});
module.exports = mongoose.model(\'Person\', personSch         


        
相关标签:
1条回答
  • 2021-02-03 11:02

    In your couple model, person1 is an ObjectID (I know you know it), so it has no obviously no property .firstname.

    Actually the best way to achieve this, is to find the the user by it's first name, and then query the couple, with the id of the user.

    This method could/should stand in the couple model as a static method (simplified code sample):

    couple.statics.findByPersonFirstname = function (firstname, callback) {
      var query = this.findOne()
    
      Person.findOne({firstname: firstname}, function (error, person) {
        query.where($or: [
          {person1: person._id},
          {person1: person._id}
        ]).exec(callback);
      })
    
      return query
    }
    

    Just like this exemple.

    EDIT: Also note that the ref must be the _id (so you couldn't store with the first name, that would be a bad idea anyway).

    Considering your edit:

    Person._id is maybe a String and the reference is an ObjectId, if so, try:

    {person1: mongoose.Types.ObjectId(Person._id)}
    

    Also, you variable is person and not Person. Try to log person to see if you get something.

    Finally, my code sample is really simple, don't forget to handle errors and all (see the link I gave you above, which is complete).

    0 讨论(0)
提交回复
热议问题