【问题标题】:how can i populate ref of own modal in mongoose我如何在猫鼬中填充自己模型的参考
【发布时间】:2020-11-30 17:48:06
【问题描述】:

我如何在 mongoose 中填充自己的模态的引用。是否可以存储自己的 ref 。当我尝试填充它时,会给出 RefrenceError。

const mongoose = require('mongoose');

const userSchema =  mongoose.Schema({
username: {
   type: String,
   required: true
},
fullname: {
   type: String,
   required: true
},
followers: [
  {
    type : mongoose.Types.ObjectId,
    ref : "User"
 }
],

});

const User = mongoose.model("User" , userSchema);

module.exports = User;

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema mongoose-populate


    【解决方案1】:

    .populate( "followers" ) 工作正常,即使您在关注者中存储对用户本身的引用。

    如果您至少显示您认为会引发错误的代码,这会容易得多。

    这是一个完整的工作示例,使用您的架构:

    // Async/await to make things simple
    async function run () {
      await mongoose.connect('mongodb://localhost', { useUnifiedTopology: true, useNewUrlParser: true })
      
      // Create, add the user to it's own followers, save.
      const user = new User({ username: 'aaa', fullname: 'bbb' })
      user.followers.push(user)
      await user.save()
    
      // Populate as usual
      const users = await User.find({})
        .populate('followers')
        .exec()
    
      // Stringify or else node will compact the output of deeply nested objects.
      console.log(JSON.stringify(users, null, 4))
    }
    
    run()
    

    【讨论】:

      猜你喜欢
      • 2015-01-13
      • 2017-09-13
      • 2021-09-19
      • 2020-07-20
      • 2021-06-29
      • 1970-01-01
      • 2014-11-01
      • 2016-04-25
      • 2018-08-03
      相关资源
      最近更新 更多