在Mongoose中保存父对象和子对象时,它存储父对象的引用,但父对象不存储对子对象的引用

时间:2020-07-10 02:45:25

标签: mongoose mongoose-populate

简而言之,问题是我在以下代码中使用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);
            });
        } 
    }

1 个答案:

答案 0 :(得分:0)

我解决了它,而解决问题的方法是使用下面的代码

const blogpost = new Blogpost( {...db_object_dict, _id: new mongoose.Types.ObjectId()} )
blogpost.save(function (err, blogpost) { // passed blogpost as well in arguments
    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);
            });
            // new added line
            blogpost.relatedcomments.push(relatedcomment._id)
        }
        // new added line
        blogpost.save() 
    }

实际上,我的错误是我没有在blogpost.relatedcomments数组中推送relatedcomment._id(子ID),然后将其保存。两者都做,我的问题就解决了。