实现填充方法以从另一个集合中存储的数组中获取ID

我有2个收藏集,分别是socialsusers。在users集合中,我有一个数组字段socialList,它将包含另一个集合中的ID。我的users集合具有一个字段lists,该字段是一个数组,并使用一些信息进行了更新。我要存储的是通过填充方法将其存储在_id集合中socialList字段中的users(此数组中的新创建数据)。

用户型号代码:-

const UserSchema = new mongoose.Schema({
    date: {
        type: Date,default: Date.now
    },socialList: [{
            type: mongoose.Schema.Types.ObjectId,ref: 'Social'
        }]
});

社交模型代码:-

const socialSchema = new Schema({
    lists: [{
        link:{ type: String},linkName: { type: String}
    }],user: {
        type: mongoose.Schema.Types.ObjectId,ref: 'User'
    }
})

社交API路线:-

 try {
           const socialListUser = await Social.find({ user: req.user.id }).populate('socialList').exec((err,socialList) => {
               console.log(`Populated User ${socialList}`)
           })
           console.log(`SocialListUser ${socialListUser}`)
    //    to create and update the lists field array
          let social = await Social.findOne({ user: req.user.id})
          if (social) {
            social = await Social.findOneAndUpdate(
                {user: req.user.id},{$push: {"lists": [req.body]}},{new: true,"safe": true} 
                )
                return res.json(`${social}`)
          }else {
            const socialList = new Social({
                user: req.user.id,lists: [req.body]
            })
            await socialList.save()
        }
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Errors')
    }
   }

我在节点终端中得到的输出是:-

SocialListUser undefined
 Populated User {
   _id: 5dc2ec3b650e4f167e4bca84,user: 5dbed60236e3e7343ac657cf,lists: [
     {
       _id: 5dc2ec3b650e4f167e4bca85,linkName: 'too',link: 'http://localhost:3000/fsd'
     }
   ],__v: 0
 }```
LT198986 回答:实现填充方法以从另一个集合中存储的数组中获取ID

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3150277.html

大家都在问