node.jsmongodbexpressmongoosemongoose-schema

Couldn't save data in to mongodb


I have two Schema in my node.js project. User and Place, one user can have many places and one place will belong to one user. so, when places is saved it will have userId with it and user with that particular userId should have that place in places property of it.

In User schema I have this code,

 //one user can have more posts [places ]
  places : [{
    type : mongoose.Types.ObjectId,
    ref : 'Place',
    required : true
}]

In Place Schema I have this code ,

//one place can only belong to one owner
owner : {
    type : mongoose.Types.ObjectId,
    ref : 'User',
    required : true
}

I am now trying to insert data into documents so that if I insert place in to the database it will have owner id [ who created that post ]. But, I am not able to save in to my database when I try to insert data from post man. Everything else works fine if I remove ({session : session }) this code inside of save method.

My code for creating new post is as follows :

const createNewPlace =  async (req,res, next) => {
const { title, description,address , rating, owner } = req.body;
let coords
try {
    coords = getCordsByAddress(address);     
} 
catch (error) {
   return next(error); 
}
const newPlace = new Place({
    title,
    description,
    address,
    location : coords,
    image : 'https://www.nepalfootprintholiday.com/wp-content/uploads/2018/12/shey-phoksundo-lodge-trek-1200x900.jpg',
    rating,
    owner
});
//before saving  check if the user who adds the place exists or not
let user;
try {
        user = await User.findById(owner);
        console.log("user", user); //yes exists ....

        //see if user not found
        if(!user) {
            return res.status(404).json({ message : "User not found. "});
        }
    } 
   catch (error) {
       return next(new HttpError('something went wrong, user not found', 500));
}
try {
    console.log("running ?", mongoose.version) //yes
    const session = await mongoose.connection.startSession();
    session.startTransaction();
    console.log("check")//no
    await newPlace.save({session : session});
    console.log("checked")  //no
    //place is added to user via its id
    user.places.push({newPlace}); //user has places property
    await user.save({session : session});
     console.log("done ? ");
    //if all line above successfully executed, it will work or undo all changes to the database.
    await session.commitTransaction();
} 
catch (error) {        
   const err = new HttpError("something went wrong, couldn't create place, ", 500);
   return next(err);
}
res.status(200).json({newPlace});

};

The line commented no or below it hasn't even executed so it is always throwing "something went wrong, couldn't create place, " . IDK what went wrong and what should I fix because there is no single error in console.

Any help with code is appreciated.


Solution

  • There were no major issues, however, when I removed the curly braces from the ...save(newPlace); and ...push(newPlace); method, and it worked as expected. It is because user.places.push({newPlace}), which is essentially same as user.places.push({newPlace: newPlace}), in this case key newPlace is not required at all. It was creating Object itself as a key and value, we just need to save the object.

    const createNewPlace =  async (req,res, next) => {
        const { title, description,address , rating, owner } = req.body;
        let coords
        try {
            coords = getCordsByAddress(address);     
        } 
        catch (error) {
           return next(error); 
        }
        const newPlace = new Place({
            title,
            description,
            address,
            location : coords,
            image : 'https://www.nepalfootprintholiday.com/wp-content/uploads/2018/12/shey-phoksundo-lodge-trek-1200x900.jpg',
            rating,
            owner
        });
        //before saving  check if the user who adds the place exists or not
        let user;
        try {
                user = await User.findById(owner);
                if(!user)  return res.status(404).json({ message : "User not found. "});
            } 
           catch (error) {
               return next(new HttpError('something went wrong, user not found', 500));
        }
        try {
            const session = await mongoose.startSession();
            session.startTransaction();
            await newPlace.save();
            user.places.push(newPlace); //user has places property
            await user.save(session);
            //if all line above successfully executed, it will work or undo all changes to the database.
            await session.commitTransaction();
        } 
        catch (error) {        
           const err = new HttpError("something went wrong, couldn't create place, ", 500);
           return next(err);
        }
        return res.status(200).json({newPlace});
    };