mongodb - How to use a field other than the primary key _id to perform a related query?
PHPz
PHPz 2017-05-31 10:35:41
0
1
1575

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)
PHPz
PHPz

学习是最好的投资!

reply all(1)
曾经蜡笔没有小新

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!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template