我如何在猫鼬中填充自己的模态的引用

问题描述

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

const mongoose = require('mongoose');

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

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

module.exports = User;

解决方法

.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()