如何在mongoose中填充自己模态的ref



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

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;

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

最新更新