我正在使用pymongo将SQLite数据库转换为MongoDB数据库。我似乎无法使用ObjectIds更新相关字段。
在javascript中,我的Articles模式如下:
const ArticleSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
category: {
type: Schema.Types.ObjectId,
ref: "Category",
required: true,
},
});
类别模型为:
const CategorySchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
weigth: {
type: Number,
required: true,
},
articles: [
{
type: Schema.Types.ObjectId,
ref: "Article",
},
],
});
数据位于数据库中,我只是获取数据并使用双联接查询对所有行进行迭代,因此我也获得了类别。我的问题是尝试将商品ID附加到python中的类别articles数组中,或等效于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'