英文:
Data type not changing in mongo DB after I made changes to mongoose schema
问题
最近我将我的mongoose模式从String
更改为Number
。当我从数据库中读取数据时,它显示为数字,但是当我尝试基于更改后的属性进行过滤时,我没有得到任何在模式更改之前保存的文档。当我使用Robo 3T进行检查时,我发现数据类型仍然显示为string
。我希望将所有数据类型都更改为数字。即使我对文档进行更新,数据类型似乎也没有改变。
以下是代码示例:
const mySchema = new mongoose.Schema({
status: {
type: Number,
default: 1
}
}...)
这是数据库中的样子:
我将非常感谢任何帮助。
英文:
I recently made changes to my mongoose schema from String
to Number
. When I read data from db, it show as Number but when I try making filters based on the changed property, I don't get any document that was saved before the schema changes were made. When I check using Robo 3T, I see the data types are still showing string
. I wish to change all to Number. The data type doesn't seem to change even after I make updates to the document.
const mySchema = new mongoose.Schema(
{
status: {
type: Number,
default: 1
}
}...)
Here is how it looks like in the DB
I'll appreciate any help
答案1
得分: 0
我从使用findOne
切换到使用findOneAndUpdate
。
mySchema.statics.updateStatus = async function(id, status){
try{
const record = await this.findOneAndUpdate({ _id:id }, {status}, {
returnOriginal: false
});
return record;
}catch(err){
return null;
}
}
这样做会更新数据库中的数据类型。
英文:
I switched from using findOne
mySchema.statics.updateStatus = async function(id, status){
try{
const record = await this.findOne({_id: id});
if(record){
record.status = parseInt(status);
}
const updatedRecord = await record.save();
return updatedRecord;
}catch(err){
return null;
}
}
To using fineOneAndUpdate
mySchema.statics.updateStatus = async function(id, status){
try{
const record = await this.findOneAndUpdate({ _id:id }, {status}, {
returnOriginal: false
});
return record;
}catch(err){
return null;
}
}
And it updated the data type in the DB.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论