Ich bin ein Neuling. Ich versuche, verschiedenen Sammlungen beizutreten, um Daten zu erhalten. Ich bin in der Lage, Post-Ersteller zu bekommen und mag Informationen, aber wie bekomme ich Beiträge mit ihren Kommentaren und Kommentatoren Informationen mit der Assoziation in mongoose?Mongoose Associations
USER Schema
const userSchema = mongoose.Schema({
username: {
type: String,
minlength: [6, 'Minimum length of username must be 6 characters'],
trim: true,
lowercase: true,
required: true,
unique: true
},
email: {
type: String,
minlength: [6, 'Minimum length of email must be 6 characters'],
trim: true,
unique: true
},
password: {
type: String,
minlength: [6, 'Minimum length of password must be 6 characters'],
required: true
},
tokens: [{
access: {
type: String
},
token: {
type: String
}
}],
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'post'
}]
}, {
timestamps: true
});
POST Schema
const postSchema = mongoose.Schema({
title: {
type: String,
trim: true,
required: true
},
body: {
type: String,
trim: true,
required: true
},
_creator: {
type: ObjectId,
ref: 'user'
},
comments: [{
type: ObjectId,
ref: 'comment'
}],
likes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}]
}, {
timestamps: true
});
KOMMENTAR Schema
const commentSchema = mongoose.Schema({
title: {
type: String,
trim: true
},
_creator: {
type: ObjectId,
ref: 'user'
},
_post: {
type: ObjectId,
ref: 'post'
}
}, {
timestamps: true
});
// get posts from all users
postRoutes.get('/', authMiddleware, async(req, res) => {
try {
const user = req.user;
const posts = await Post.find({})
.populate('_creator likes comments')
.sort({
createdAt: -1
})
.limit(1);
return res.send(posts);
} catch (e) {
return res.status(400).send(e);
}
});
ich nur c bekommen IDs, aber ich möchte Kommentare mit ihren Informationen. Was mache ich falsch? json_object_image
haben einen Blick auf diese Lösung hilfreich [link] sein könnte (https://stackoverflow.com/a/7813331/7372769) – Ayush
'comment = erwarten comment.save(); // Ich habe diese Zeile zuvor nicht hinzugefügt, daher wurden Kommentare nicht gespeichert. post.comments.push (Kommentar._ID); post = erwarten post.save(); ' –