Rather than using methods chain and callback, from express router we can call to mongoose findOne using async await as following
we can then search for mongo, if found then use the object, not found then create new one and attach to the second entity.
// mongoose.model("Child", ChildSchema);
// mongoose.model("Parent", ParentSchema);
router.post('/create', async function (req, res, next) {
const user = req.user;
const childObject = req.body.object1;
const parentObject = req.body.object2;
console.log('create parent-child for user: ', user, ' from parent: ', parentObject, 'to child:', childObject);
var parentEntity = await Parent.findOne({criteria1: parent.value1}).exec();
if(!parentEntity) {
parentEntity = new Parent(parentObject);
parentEntity.extra = 'extra';
parentEntity.userId = user.id;
parentEntity.save();
}
var childEntity = await Child.findOne({criteria1: child.value1}).exec();
if(!childEntity) {
childEntity = new Child(child);
childEntity.extra = 'extra';
childEntity.userId = user.id;
childEntity.parentId = parentEntity.id;
childEntity.save();
}
});
This helps us solve the express mongoose mongodb object dependency issue
Add to my src(0) Please login to bookmark
No account yet? Register