[英]object reference using mongoose
var express = require("express"); var mongoose=require("mongoose"); // comment schema var commentsSchema=new mongoose.Schema({ text:String }); var comment=mongoose.model("text",commentsSchema); // post schema var postsSchema=new mongoose.Schema({ posts:String, texts:[ { type:mongoose.Schema.Types.ObjectId, ref:'text' } ] }); var posts=mongoose.model("post",postsSchema); // post route app.get('/home',function(req,res){ posts.find({},function(err,posts){ if(err){ console.log(err); } else { // console.log(posts); res.render("index.ejs",{posts:posts}); } }); }); // post route app.post('/home',function(req,res){ posts.create({posts:req.body.post,username:req.user.username},function(err,post){ if(err){ console.log(err); } else { console.log("new post created"); res.redirect("/home"); } }); }); // comment route:- in this route i created comment pushed into post schema app.post('/home/:id/comments',function(req,res){ posts.findById(req.params.id,function(err,post){ if(err){ console.log(err); } else { var com=req.body.comment; var user=req.user.username; console.log(com); var com1={text:com,username:user}; comment.create(com1,function(err,newComment){ if(err){ console.log("err"); } else{ console.log(newComment); post.texts.push(newComment); post.save(); console.log(post); res.redirect("/home"); } }); } }); });
<% posts.slice().reverse().forEach(function(post){ %> post.texts.forEach(function(comment){ <%= comment.text %> // error:- showing object id instead of text }); <% }); %>
<%= comment.text %>
-----此html行显示的是objectId(ex:-5b5bf9afc21a414b54ab3290)
而不是在html页面上的注释。发布架构和注释架构是否正确关联? 如果它们是为什么我要在HTML页面而不是数据库中的注释上获取objectId
。
这是数据库中的注释对象
{ _id: 5b5bf9afc21a414b54ab3290,
text: 'hey',
username: 'yashwanth',
__v: 0 }
这是数据库中的发布对象,其中包含注释对象的对象引用
{ texts:
[ { _id: 5b5bf9afc21a414b54ab3290,
text: 'hey',
username: 'yashwanth',
__v: 0 } ],
_id: 5b5bf9a9c21a414b54ab328f,
posts: 'lol',
username: 'yashwanth',
__v: 0 }
如果您使用猫鼬的“ ref”属性,则必须使用猫鼬填充查询和查找查询来填充带有注释模式的帖子模式。 试试看,这肯定会解决您的问题。
您将需要填充子架构(文本)
请仔细阅读本文档
http://mongoosejs.com/docs/populate.html#population
posts.find({}).
populate('texts').
exec(function (err, posts) {...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.