Mongoose save() not working/saving

If save() does not save the entity to mongodb database, probably there’s something wrong with the data itself like containing _id field

delete data._id; //clean up to ensure no _id field.
let user = new User(data);
user.save();

Also it is better to provide error handling so we can read what went wrong using the log.

let user = new User(data);
user.save(function (err) {
            if (err) {
                console.log(err);
            }
        });
Add to my src(1)

No account yet? Register

Return value from Mongoose findOne sync call (parent-child dependency entity)

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)

No account yet? Register