search

Home  >  Q&A  >  body text

mongodb - How to use a field other than the primary key _id to perform a related query?

Now there is an article post model that uses cateId to associate with the Category category. But cateId is not _id. Resulting in an error when retrieving.
Can we only associate through _id? How to use non-_id under Category to associate?

var PostSchema = new mongoose.Schema({
    author: { type: mongoose.Schema.Types.ObjectId},
    title: String,
    content: String,
    imgUrl: String,
    pv: { type:Number, default:0}, 
    like: { type:Number, default:0}, 
    keep:  { type:Number, default:0}, 
    comments: { type:Number, default:0}, 
    cateId: { type:Number, ref:'Category'},
    type:  Number,
    create_date: { type: Date, default: Date.now }
},{
    versionKey: false 
})

var Post = mongoose.model('Post', PostSchema)
PHPzPHPz2727 days ago1551

reply all(1)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-31 10:37:41

    1, Mongoose’s populate can only be on _id;

    2. Therefore, you can only write your own code for association here. First query one collection, then query another collection, and associate it yourself.

    For reference.

    Love MongoDB! Have fun!


    The 2017 MongoDB Chinese Community Beijing User Group Conference is coming soon, June 3, 2017 13:00-18:00

    Registration now! Please click on the left!

    reply
    0
  • Cancelreply