我如何在猫鼬中填充自己模态的引用
how can i populate ref of own modal in mongoose
如何在 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;
.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()
如何在 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;
.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()