pymongo.errors.InvalidOperation:执行查询后无法设置选项

2022-03-14 00:00:00 python string flask mongodb pymongo

问题描述

我正在处理一个使用flask和pymongo的项目,我有一个Users集合和一个Movies集合,其中的实例如下:

 user = {"Email":"user@gmail.com" , "Comments":[" Hobbit 2013 :good movie" , " Hobbit 2013 :bad movie" , " Spiderman 2020 :very good"]}

我还有一个电影集合,其中的电影实例如下:

movie = {"title":"Hobbit" , "year":"2013" , "comments":["Hobbit 2013 user@gmail.com:good movie"] }
我正在使用JJJA 2模板提交特定电影的新片名,如果有任何用户评论了该电影,我希望每个评论该电影的用户在其评论中都有新的电影名称 例如。Hobbit->;然后为上述用户实例复仇者

`user = {"Email":"user@gmail.com" , "Comments":[" Avengers  2013 :good movie" , " Avengers 2013 :bad movie" , " Spiderman 2020 :very good"]}`  
`movie = {"title":"Avengers" , "year":"2013" , "comments":["Avengers 2013 user@gmail.com:good movie"] }` #obviously a movie can have more comments from users not just one 

使用烧瓶端点,我成功地更改了电影标题,但是我无法更改旧电影标题所在的任何用户评论,因为标题不会随我的代码更改

这是我的终结点。我从JJAA2表单获得新标题,然后尝试用新标题替换评论中的旧标题。然后我收到错误

pymongo.errors.InvalidOperation: cannot set options after executing query

我的代码:

@app.route('/executemovieupdate' , methods = ['GET', 'POST'])
def execute_movie_update():
    if 'Email' in session and 'User' in session:
        email = session['Email']
        user = session['User']
        if user == 'Admin':
            if 'Movie' in session and 'Movie_year' in session and 'Movie_plot' in session:
                movie = session['Movie']
                old_movie  = str(movie) #store old movie title 
                print("old movie is " , old_movie)
                year = session['Movie_year']
                plot = session['Movie_plot']
                tainia = movies.find_one({'title':movie , "year":year})
                if request.method == 'POST':
                    new_title = request.form.get('new-title') #get the new title from jinja2 template 

            

                    if new_title:
                       print("update the title")
                       movies.update_one({"title":movie , "year":year} , {"$set":{"title":new_title} } ) #the title is updated succesfully for the movie 
                       session['Movie'] = new_title
                       movie = session['Movie']
                       user_list = users.find({})
                       for idxu, usr in enumerate(user_list): #this is where i try to change the title in the user comments 
                            for idxc, comment in enumerate(usr['Comments']):
                                if  old_movie in comment:
                                    print("old comment here")
                                    print(comment)
                                    user_list[idxu]['Comments'][idxc] = comment.replace(old_movie ,new_title) #this is the line where the error occurs
                                    print(comment) # the new comment is printed

                    return ''' movie has been updated '''
                                                                                                      
            else:
                return render_template('movie-update.html' , movie = tainia)        
        else:
            return redirect(url_for('admin.html'))    
    else:
        return redirect(url_for('login')) 
else:
    return redirect(url_for('login'))    

感谢您在这个问题上的帮助。提前感谢您。


解决方案

如果打印type(user_list),您会注意到它不是dict的列表,而是一个pymongo.cursor.Cursor对象(它是只读的),因此您可以将user_list = users.find({})更改为user_list = list(users.find({}))(但要小心,它将查询集合users中的所有记录),它应该可以工作。

另一种更好的方法是使用usr['Comments'][idxc](这是dict)而不是user_list[idxu]['Comments'][idxc]

如果要将该记录更新到MongoDB中,则需要使用上述update_one

我没有您的数据,但这样的数据应该可以解决问题:

for idxu, usr in enumerate(user_list): #this is where i try to change the title in the user comments 
    for idxc, comment in enumerate(usr['Comments']):
        if  old_movie in comment:
            print("old comment here")
            print(comment)
            usr['Comments'][idxc] = comment.replace(old_movie ,new_title) #this is the line where the error occurs
            print(comment) # the new comment is printed
    users.update_one({"_id": usr['_id']}, {"$set": {"Comments": usr['Comments']}})

相关文章