简体   繁体   中英

How to populate a mongoose schema

I have the following mongoose schemas

var postTable = mongoose.Schema({
userPost:{type : String},
dateCreated: {type: Date, default: Date.now},
_replies:[{type: mongoose.Schema.Types.ObjectId, ref: 'reply_table'}],
_creator:{type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});

and

var reply_table = mongoose.Schema({
userReply:{type:String},
date_created:{type:Date, default: Date.now},
_post:{type: mongoose.Schema.Types.ObjectId, ref: 'post'},
_creator:{type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});
var userPost = module.exports = mongoose.model("Post",postTable);

var userReply = module.exports = mongoose.model('reply_table',reply_table);

User can create post which will be entered into the Post table and other users can comment or reply to a post which will be entered into the reply_table. I then try to populate the the post table like this

module.exports.getPost = function (callback) {
var mysort = { dateCreated: -1 };
userPost
    .find({},callback)
    .sort(mysort)
    .populate('_creator','username')
    .populate(' _replies')
    .exec(function (err,post) {
        if(err) throw err;
        console.log(post)
    });
  };

When the console prints out the post it prints the post information and a object with the user information becausei have another schema setup for users, therefore I used .populate('_creator','username')

The problem is it wont print the reply information it only prints an empty array: reply[].

I'm pretty sure I'm doing everything right. I used the following code to insert information into the reply_table

//make a reply on a post
module.exports.make_reply = function (user_id,pid,reply,callback) {
var newReply = userReply({
    _creator: user_id,
    _post: pid,
    userReply: reply
});
newReply.save(callback);
}

I know this question is very long but does anyone have any idea of what I might be doing wrong. I only want to populate the Post schema with information from the reply_table

I finally figured out a solution to my question. What i did was i created a function to insert the reply id into the post table. It basically get the comment by its id and push a reply into the _replies array in the post table.

//Insert reply into post table
 module.exports.addReply = function (id,reply) {
 userPost.update({_id:id},{$push:{replies:reply}},{multi:true},function 
(err,post) {
});
}

When i use the getPost function it populates the reply table

module.exports.getPost = function (callback) {
var mysort = {dateCreated: -1};
userPost
    .find({}, callback)
    .sort(mysort)
    .populate('_creator', 'username')
    .populate('replies')
    .exec(function (err) {
        if(err) throw err;
    });
   };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM