我有一個食譜博客網站,每個食譜都有評論。每條評論都保存到評論集合中,但是當我將評論推送到正確的配方時,不僅僅是保存 ObjectID。這是我的代碼:
配方型號
const { Double } = require('bson');
const mongoose = require('mongoose');
const recipeSchema = new mongoose.Schema({
name: {
type: String,
required: 'This field is required.'
},
description: {
type: String,
required: 'This field is required.'
},
quantity: {
type: Array,
required: 'This field is required.'
},
ingredients: {
type: Array,
required: 'This field is required.'
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}
],
recipe_id: {
type: String,
}
});
recipeSchema.index({ name: 'text', description: 'text' });
const Recipe = module.exports = mongoose.model('Recipe', recipeSchema);
評論模型
const commentSchema = new mongoose.Schema({
username: {
type: String,
required: 'This field is required.'
},
comment: {
type: String,
required: 'This field is required.'
},
recipe_id: {
type: String
}
});
路線
router.get('/', recipeController.homepage);
router.get('/recipe/:id', recipeController.exploreRecipe );
router.get('/categories/:id', recipeController.exploreCategoriesById);
router.get('/categories', recipeController.exploreCategories);
router.get('/submit-recipe', recipeController.submitRecipe);
router.post('/submit-recipe', recipeController.submitRecipeOnPost);
router.post('/recipe/:id/comments', recipeController.CommentRecipeOnPost);
控制器
module.exports.CommentRecipeOnPost = async(req, res) => {
const comment = new Comment({
username: req.body.username,
comment: req.body.comment
});
comment.save((err, result) => {
if (err){
console.log(err)
}else {
Recipe.findById(req.params.id, (err, post) =>{
if(err){
console.log(err);
}else{
post.comments.push(result);
post.save();
console.log('====comments=====')
console.log(post.comments);
res.redirect('/');
}
})
}
})
}
我嘗試了 populate 和另一種方法,但沒有人作業,經過很多小時的編程,我完成了這些,我只能保存 ObjectId-s。
uj5u.com熱心網友回復:
這是因為你定義的評論在配方模式作為的ObjectId那是正確的,如果你想獲得完整評論引數,你會填充記錄
const recipe = await Recipe.findOne({ _id: "recordId"}).populate("posts")
這將回傳所有評論詳細資訊
{ name: "Fitness recipe", description: "Fitness recipe to loss 10kg in 10 days only", comments: [ {_id: "recordId", username: "Smith June", comment: "That's awesome"}]}
如果您需要將整個檔案保存為一個物件陣列,而不僅僅是 id,那么您可以創建這樣的架構
const recipeSchema = new mongoose.Schema({
name: {
type: String,
required: 'This field is required.'
},
description: {
type: String,
required: 'This field is required.'
},
quantity: {
type: Array,
required: 'This field is required.'
},
ingredients: {
type: Array,
required: 'This field is required.'
},
comments: [
{ username: String, comment: String }
],
recipe_id: {
type: String,
}
})
在這種情況下,您不會有任何關系,您可以輕松列出食譜評論。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377448.html
標籤:javascript 节点.js 表达 猫鼬 推
下一篇:貓鼬批量更新
