freethrow
freethrow

Reputation: 1108

How can I append an ObjectID in an array through Pymongo?

I am converting a SQLite database to a MongoDB database using pymongo. I can't seem to be able to update the related fields with the ObjectIds.

In javascript, my Articles schema is the following:

const ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  body: {
    type: String,
    required: true,
  },
  category: {
    type: Schema.Types.ObjectId,
    ref: "Category",
    required: true,
  },
});

And the categories model is:

const CategorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  weigth: {
    type: Number,
    required: true,
  },
  articles: [
    {
      type: Schema.Types.ObjectId,
      ref: "Article",
    },
  ],
});

The data is in a database and I just fetch it and iterate over all the rows with a double join query, so I get the category as well. My problem is trying to append the article id to the category articles array in python, or the equivalent of a javascript push. The code that I am trying is the following:

for row in rows:
    # get the category
    cat = categories.find_one({'name': row[4]})

    cat_id = str(cat['_id'])
    # populate the article
    article = {
        'title': row[0],
        'body': row[1],
        'category': str(cat["_id"])
    }

    id = articles.insert_one(article).inserted_id

    categories.update({
        '_id': cat_id
    },
        {
        '$push': {'articles': id}}
    )

Upvotes: 1

Views: 398

Answers (1)

bathman
bathman

Reputation: 305

Your update query never matches the _id of the category.

If you replace cat_id = str(cat['_id']) by cat_id = cat['_id']

then it should work. because your categories.update({'_id': cat_id}) does not match the ID since you don't query for ObjectId but for a string. Or in other words ObjectId('5ea48b3743183ad74f6987bc') != '5ea48b3743183ad74f6987bc'

Upvotes: 2

Related Questions