无法将数据保存到mongodb

问题描述 投票:0回答:1

我的node.js 项目中有两个架构。用户和地点,一个用户可以拥有多个地点,一个地点属于一个用户。 因此,当保存地点时,它将包含 userId,并且具有该特定 userId 的用户应该在其 place 属性中拥有该地点。

在用户模式中我有这个代码,

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

就地架构我有这个代码,

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

我现在正在尝试将数据插入到文档中,这样如果我将位置插入到数据库中,它将具有所有者 ID [创建该帖子的人]。但是,当我尝试从邮递员插入数据时,我无法保存到我的数据库中。如果我删除保存方法中的

({session : session })
这段代码,其他一切都会正常工作。

我创建新帖子的代码如下:

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});

};

该行注释为 no 或下面它甚至还没有执行,所以它总是抛出

"something went wrong, couldn't create place, "
。我不知道出了什么问题,我应该修复什么,因为控制台中没有任何错误。

任何有关代码的帮助都将不胜感激。

node.js mongodb express mongoose mongoose-schema
1个回答
0
投票

但是,当我从

...save(newPlace);
...push(newPlace);
方法中删除大括号时,没有出现重大问题,并且它按预期工作。 这是因为
user.places.push({newPlace})
,本质上与
user.places.push({newPlace: newPlace})
相同,在这种情况下根本不需要密钥newPlace

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});
};
© www.soinside.com 2019 - 2024. All rights reserved.