Mongoose populate 與多張表多級關聯查詢

async function getinfo (userid) {
    let postinfo,collectinfo;
    try {
        postinfo = await userModel.findOne({'userId':userid}).populate({path:'post',select:' -__v -visit -star -reply -anthorDesc -author '});
        collectinfo  = await userModel.findOne({'userId':userid}).populate({path:'collect',select:' -__v -visit -star -reply -anthorDesc -author '});
    } catch (error) {
        throw error
    }
    postinfo.collect = [];
    console.log(collectinfo.collect);
    postinfo.collect = postinfo.collect.concat(collectinfo.collect);
    return postinfo
}

查詢一個用戶的發帖與收藏帖子的情況

model如下

var userSchema = new Schema({
    "userId":{type:String},
    "name" : {type:String},
    "password" : {type:String},
    "email":{type:String},
    "intro":{type:String,default:'他還沒有任何介紹!'},
    "avatar":{type:String,default:'userAvatar.png'},
    "collect":[{type:mongoose.Schema.Types.ObjectId,ref:'Post'}],
    "post":[{type:mongoose.Schema.Types.ObjectId,ref:'Post'}],
    "isAdmin":{type:Boolean,default:false},//判斷是否爲管理員
});

通過assign進行復制存在問題

用contact方法進行連接時,如果不清空被連接的數組,便不能得到正確的結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章