How to set ObjectId as a data type in mongoose

前端 未结 4 1727
感动是毒
感动是毒 2020-12-07 11:31

Using node.js, mongodb on mongoHQ and mongoose. I\'m setting a schema for Categories. I would like to use the document ObjectId as my categoryId.

var mongoos         


        
4条回答
  •  情深已故
    2020-12-07 11:59

    I was looking for a different answer for the question title, so maybe other people will be too.

    To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

    const Book = mongoose.model('Book', {
      author: {
        type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                              // from the Author colection, 
                                              // so you can reference it
        required: true
      },
      title: {
        type: String,
        required: true
      }
    });
    

提交回复
热议问题