0

To begin, I have checked all these links, but none of them helped.

Insert an element into an array of nested model Mongodb with PyMongo on FASTAPI

Inserting an object inside an array fails

how to insert an object to array in mongodb database

MongoDB - Update or Insert object in array

So I have the document schema that looks like this:

Documnent Schema

Postings is an array of Posting objects, which have this schema:

Posting Schema

_id and timestamp are automatically generated, so the body of the request looks like this

{
    "title" : "new posting",
    "totalNumOfRoommates" : 17
}

My issue is that i cannot insert a new Posting Object, this is what I have tried thus far:

@router.post('/', response_description='Creates a posting for a specified user', response_model=postingModel.Posting)
async def addPost(post: postingModel.Posting = Body(...), userId: str = ""):
    user = await dbConnection.find_one({"_id" : userId})
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="User ID was not provided or was wrong, please provide it as a query parameter Example: http://127.0.0.1:8000/api/postings?userId=abcd-1234-efgh-5678",
        )
    
    post = jsonable_encoder(post)
    update_result = await dbConnection.update_one({"_id": id}, {"$push" : {"postings" : post} })

post looks exactly how I expect it to be, which is:

{
   '_id': '6de685e7-d55f-4412-99e1-adf03f013cdd', 
   'timestamp': '2022-10-19T16:44:23.190900', 
   'title': 'new posting', 
   'totalNumOfRoommates': 17
}

My question is, how can I insert an object into an array of objects using Python/FastAPI

Edit: The stack trace is included below

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 404, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\fastapi\applications.py", line 270, in __call__    
    await super().__call__(scope, receive, send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\applications.py", line 124, in __call__  
    await self.middleware_stack(scope, receive, send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\middleware\exceptions.py", line 75, in __call__
    raise exc
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\middleware\exceptions.py", line 64, in __call__
    await self.app(scope, receive, sender)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in 
__call__
    raise e
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in 
__call__
    await self.app(scope, receive, send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\routing.py", line 680, in __call__       
    await route.handle(scope, receive, send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\routing.py", line 275, in handle
    await self.app(scope, receive, send)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\starlette\routing.py", line 65, in app
    response = await func(request)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\fastapi\routing.py", line 231, in app
    raw_response = await run_endpoint_function(
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\fastapi\routing.py", line 160, in run_endpoint_function
    return await dependant.call(**values)
  File "D:\Bilkent Uni\Courses\CS 491\BilMate\Backend\.\postings\PostingEndpoints.py", line 26, in addPost
    update_result = await dbConnection.update_one({"_id": id}, {"$push" : {"postings" : post} }, upsert=True)
  File "C:\Python39\lib\concurrent\futures\thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\collection.py", line 1019, in update_one   
    self._update_retryable(
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\collection.py", line 868, in _update_retryable
    return self.__database.client._retryable_write(
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\mongo_client.py", line 1498, in _retryable_write
    return self._retry_with_session(retryable, func, s, None)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\mongo_client.py", line 1384, in _retry_with_session
    return self._retry_internal(retryable, func, session, bulk)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\mongo_client.py", line 1416, in _retry_internal
    return func(session, sock_info, retryable)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\collection.py", line 860, in _update       
    return self._update(
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\collection.py", line 829, in _update       
    result = sock_info.command(
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\pool.py", line 699, in command
    self._raise_connection_failure(error)
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\pool.py", line 683, in command
    return command(self, dbname, spec, slave_ok,
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\network.py", line 120, in command
    request_id, msg, size, max_doc_size = message._op_msg(
  File "d:\bilkent uni\courses\cs 491\bilmate\backend\virenv\lib\site-packages\pymongo\message.py", line 714, in _op_msg
    return _op_msg_uncompressed(
bson.errors.InvalidDocument: cannot encode object: <built-in function id>, of type: <class 'builtin_function_or_method'>
6
  • " i cannot insert " - why not? Commented Oct 19, 2022 at 14:02
  • what i meant to say is, when inserting, it does not work Commented Oct 19, 2022 at 14:14
  • 1
    Yes, this part is clear, you don't get the expected result. What I asked is to clarify what you get instead. Any errors? Commented Oct 19, 2022 at 14:35
  • 2
    I'll let @AlexBlex write up the answer if they want, but the relevant portion of the error is cannot encode object: <built-in function id>. When you retrieve the data you are doing so with .find_one({"_id" : userId}). But when you go to write it you have .update_one({"_id": id},. I think that last id should be userId. Commented Oct 19, 2022 at 15:15
  • 1
    Cheers @user20042973 for picking it up. Just to confirm we don't intend to answer as it's clearly a typo and the answer won't bring much to the community. Commented Oct 19, 2022 at 15:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.