relations in mongoose with custom field

后端 未结 3 1784
说谎
说谎 2021-01-25 13:24

I\'ve seen many examples about mongoose and relations, but how can I create a reference to another entity into a custom field ?

var mongoose = require(\'mongoose         


        
3条回答
  •  自闭症患者
    2021-01-25 13:46

    No, you can't. Mongoose always use _id field to link documents. But...

    You can set your own _id for each document, using any datatype you want. There are only two restrictions:

    • it should be unique
    • it should not be changed during document's lifetime

    So, instead of adding new slugname field, use author's _id as a slugname:

    var Author = m.model('Author', new m.Schema({
      _id: String, // <-- slugname
      name: String
    }));
    var Book = m.model('Book', new m.Schema({
      title: String,
      author: { type: String, ref: 'Author' }
    }));
    

提交回复
热议问题