node.js - 查找 ObjectId _id 但 Schema 已将 _id 定义为 String
问题描述
以前我没有_id
在我的 Schema 中声明 ,所以每个新提交自然都会生成 MongoDB ObjectId
,因为它是_id
. 但是,要求已经改变,现在_id
声明String
如下。
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var MySchema = new Schema({
_id: {
type: String,
},
schoolID: {
type: mongoose.Schema.Types.ObjectId, ref: 'School'
},
points: {
type: Number
},
});
MySchema.index({ schoolID : 1})
module.exports = mongoose.model('Submission', MySchema);
但是,现在我根本找不到以前插入的文档_id
。我试过
var submissionId = "60654319a8062f684ac8fde4"
Submission.findOne({ _id: mongoose.mongo.ObjectId(submissionId ) })
Submission.findOne({ _id: mongoose.Types.ObjectId(submissionId ) })
Submission.findOne({ _id: mongoose.ObjectId(submissionId ) })
但它总会回来null
的。所以当我使用var mongoose = require('mongoose').set('debug', true);
检查时,它会显示在下面;我上面的所有查询仍然会找到 using String
,而不是ObjectId
Mongoose: submission.findOne({ _id: '60654319a8062f684ac8fde4' }, { projection: {} })
解决方案
问题 -_id: { type: String,},
猫鼬会在查询数据库之前转换值,所以在你的情况下,它总是一个字符串。
选项1
当您计划使用 String 时,将旧的 objectId 转换为 String,_id
因此最好保持一致。
从 shell Robomongo 运行这些命令
_id
这将为现有记录添加带有字符串的ObjectId
记录。
db.collection.find({}).toArray() // loop all records
.forEach(function (c) {
if (typeof c._id !== 'string') { // check _id is not string
c._id = c._id.str; db.collection.save(c); // create new record with _id as string value
}
});
删除记录ObjectId
db.collection.remove({ _id: { $type: 'objectId' } })
选项-2
添加 Mongoose 自定义类型。
https://mongoosejs.com/docs/customschematypes.html
class StringOrObjectId extends mongoose.SchemaType {
constructor(key, options) {
super(key, options, 'StringOrObjectId');
}
convertToObjectId(v) {
const checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
let _val;
try {
if (checkForHexRegExp.test(v)) {
_val = mongoose.Types.ObjectId(v);
return _val;
}
} catch (e) {
console.log(e);
}
}
convertToString(v) {
let _val = v;
try {
if(_.isString(_val)) return _val;
if(_.isNumber(_val)) return _.toString(_val);
} catch (e) {
console.log(e);
}
}
cast(val) {
const objectIdVal = this.convertToObjectId(val);
if (objectIdVal) return objectIdVal;
const stringVal = this.convertToString(val)
if (stringVal) return stringVal;
throw new Error('StringOrObjectId: ' + val +
' Nor string nor ObjectId');
}
}
mongoose.Schema.Types.StringOrObjectId = StringOrObjectId;
var MySchema = new Schema({
_id: {
type: StringOrObjectId, // custom type here
},
schoolID: {
type: mongoose.Schema.Types.ObjectId, ref: 'School'
},
points: {
type: Number
},
});
询问
Submission.findOne({ _id: submissionId }); // it will cast ObjectId or String or throw error
缺点
- 如果您的 _id 类型字符串是
60516ae1ef682d2804a2fa72
有效ObjectId
的,它将转换为ObjectId
与记录不匹配的字符串。
注意 - 这是一个粗略的课程StringOrObjectId
,添加适当的检查并正确测试。
选项-3
简单的方法 - 使用mongoose.Mixed
https://mongoosejs.com/docs/schematypes.html#mixed
https://mongoosejs.com/docs/api.html#mongoose_Mongoose-Mixed
cont MySchema = new Schema({
_id: {
type: mongoose.Mixed,
},
schoolID: {
type: mongoose.Schema.Types.ObjectId, ref: 'School'
},
points: {
type: Number
},
});
推荐阅读
- java - 将 kafka 中的 Avro 反序列化为 SpecificRecord 失败。期望类型是 PojoTypeInfo
- python - 如何使用带有 key_generator 的随机循环?
- typescript - 嵌套数据获取 fp-ts 末日金字塔
- mysql - 模拟 SQL 查询
- database - 如何添加在所有更新完成后运行的触发器
- c++ - 运行 main.cpp 函数时,Visual Studio 2019 中出现错误 MBS4019
- ruby-on-rails - ActionCable 在反应组件中不起作用
- python - 使用循环顺序调用函数 Python
- html - 如何将列表水平放置在不同的元素旁边(例如输入元素)
- graphql - Django GraphQL Mutation 更新,但数据库没有变化