簡體   English   中英

如何通過 Pymongo 在數組中 append 一個 ObjectID?

[英]How can I append an ObjectID in an array through Pymongo?

我正在使用 pymongo 將 SQLite 數據庫轉換為 MongoDB 數據庫。 我似乎無法使用 ObjectIds 更新相關字段。

在 javascript 中,我的文章架構如下:

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

類別 model 是:

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

數據在數據庫中,我只是獲取它並使用雙連接查詢遍歷所有行,所以我也得到了類別。 我的問題是嘗試將 append 的文章 ID 轉換為 python 中的類別文章數組,或等效於 javascript push 我正在嘗試的代碼如下:

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

您的更新查詢永遠不會與類別的 _id 匹配。

如果將cat_id = str(cat['_id'])替換為cat_id = cat['_id']

那么它應該可以工作。 因為您的categories.update({'_id': cat_id})與 ID 不匹配,因為您不查詢ObjectId而是查詢string 或者換句話說ObjectId('5ea48b3743183ad74f6987bc') != '5ea48b3743183ad74f6987bc'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM