【问题标题】:Couldn't save data in to mongodb无法将数据保存到 mongodb
【发布时间】:2020-11-04 17:35:54
【问题描述】:

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

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

 //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, " 。 IDK 出了什么问题,我应该解决什么问题,因为控制台中没有单个错误。

感谢任何有关代码的帮助。

【问题讨论】:

  • 抓到它们时看不到错误
  • @prabhu 那我该怎么办?你有什么解决办法吗?

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

我解决了这个问题如下。没有大问题,但是当我从 ...save(newPlace);...push(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);
            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.startSession();
        session.startTransaction();
        console.log("check")//no
        await newPlace.save();
        console.log("checked")  //no
        //place is added to user via its id
        user.places.push(newPlace); //user has places property
        console.log("pushed")
        await user.save(session);
         console.log("done ? ");
        //if all line above successfully executed, it will work or undo all changes to the database.
        await session.commitTransaction();
        console.log("done ,yes");

    } 
    catch (error) {        
       const err = new HttpError("something went wrong, couldn't create place, ", 500);
       return next(err);
    }
    return res.status(200).json({newPlace});
};

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多