【发布时间】:2020-07-10 16:52:26
【问题描述】:
简而言之,问题是我正在使用带有以下代码的 Mongoose 在父架构 Blogpost 和子架构 Relatedcomment 中创建和保存数据库条目,但是当我查询它时,父对象的 _id 确实显示在子对象中,但是in the parent object no child shows up at all。换句话说the child knows who the parent is, but the parent doesnt know who is its child。请帮我解决如何到达子对象while querying parent object。代码如下
以下是父对象的架构,即 Blogpost
blogpost.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BlogpostSchema = new mongoose.Schema({
_id: Schema.Types.ObjectId,
image:String,
title:String,
related_comments: [{ type: Schema.Types.ObjectId, ref: 'Relatedcomment' }],
});
mongoose.model('Blogpost', BlogpostSchema);
下面是子对象的架构,即Relatedcomment
relatedcomment.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RelatedcommentSchema = new mongoose.Schema({
blogpost: { type: Schema.Types.ObjectId, ref: 'Blogpost' },
user_name: String,
comment: String,
});
mongoose.model('Relatedcomment', RelatedcommentSchema);
下面是我如何保存父对象和子对象。观察我将 _id 传递给 blogpost,它的孩子也传递给 blogpost._id
require('../models/blogpost');
require('../models/relatedcomment');
const Blogpost = mongoose.model('Blogpost');
const Relatedcomment = mongoose.model('Relatedcomment');
// db_object_dict and child_db_object_dict are objects containing key value pairs according to their schemas
const blogpost = new Blogpost( {...db_object_dict, _id: new mongoose.Types.ObjectId()} )
blogpost.save(function (err) {
if (err) return handleError(err);
const related_child = new Relatedcomment( {...child_db_object_dict, blogpost: blogpost._id} )
related_child.save(function (err) {
if (err) return handleError(err);
});
}
}
【问题讨论】:
标签: mongoose mongoose-populate