使用Mongoose在MongoDB中将字符串字段转换为ObjectID字段 [英] Convert String fields to ObjectID fields in MongoDB using Mongoose
本文介绍了使用Mongoose在MongoDB中将字符串字段转换为ObjectID字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有两种模式的MongoDB数据库-用户和帖子.过去看起来像这样:
I have a MongoDB database with two schemas - users and posts. It used to look like this:
username: {type: String},
following: {type: [String], ref: 'users'}
user_id: {type: String, ref: 'users'}
comment: {type: String}
但是现在我决定将引用字段的类型从String更改为ObjectId,所以现在有了:
But now I've decided to change reference fields' types from String to ObjectId so now I have:
username: {type: String},
following: {type: [Schema.Types.ObjectId], ref: 'users'}
user_id: {type: Schema.Types.ObjectId, ref: 'users'}
comment: {type: String}
但是数据库中的旧数据仍然存储为字符串.如何正确迁移这些数据?
But the old data in the database is still stored as Strings. How can I migrate that data properly?
我用Mongoose从我的代码中查询数据库.
I use Mongoose to query the database from my code.
推荐答案
您应该使用 model.find({})来获取所有发布的文档,然后循环遍历每个文档并更新每个文档
You should use model.find({}) to fetch all the post documents and after that loop through each document and update each document
doc.user_id = mongoose.Types.ObjectId(doc.user_id);
doc.save();
这篇关于使用Mongoose在MongoDB中将字符串字段转换为ObjectID字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文