简体   繁体   中英

mongoose generating a children field using parent field

I am trying to create a family tree website using mongodb. upon creating a new family member, i only want to reference the parent (father) of the person and have mongoose automatically generate a children field in the person model. Here is the Person schema:

Person.add({
    fullName: { type: String, initial:true, required: true,label: , index:true,  },
    parent: {type: Types.Relationship, ref:'Person'},
});

As you can see, upon creating a new person, I would want mongoose to automatically find all people in the Person model with the parent id matching the person I'm creating and generate an array of ids in the children field.

I have done some researches and found that Mongoose Virtuals can provide something like that but i have not found any documentation regarding querying the model to add to the virtual field. Thanks in advance!

You can create a post save hook in your Person schema model, and then find the people with parent id and create/update children array of that person.

use $addToSet instead of $push so that same childrens are not pushed more than once.

Try this:

PersonSchema.post('save', function(doc, next) {
    this.findOneAndUpdate({_id : doc.parent},{$addToSet : { children : doc._id}})
    next();
});

Read more about mongoose hooks for detailed information.

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