首页 > 解决方案 > 查找 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: {} })

标签: node.jsmongodbmongoosemongodb-querymongoose-schema

解决方案


问题 -_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
    },
});

推荐阅读