我试着让ULID和猫鼬一起工作。
我的DocTypeA模式如下所示:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ULID = require('ulid')
const schema = new Schema({
_id: { type: Schema.Types.String, default: () => ULID.ulid(Date.now()) },
name: { type: Schema.Types.String },
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
transform: function (doc, ret) {
// remove these props when object is serialized
delete ret._id
},
})
module.exports = mongoose.model('DocTypeA', schema)我的DocTypeB模式如下所示:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ULID = require('ulid')
const schema = new Schema({
_id: { type: Schema.Types.String, default: () => ULID.ulid(Date.now()) },
name: { type: Schema.Types.String },
docA: { type: Schema.Types.ObjectId, ref: 'DocTypeA' },
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
transform: function (doc, ret) {
// remove these props when object is serialized
delete ret._id
},
})
module.exports = mongoose.model('DocTypeB', schema)我能够为DocTypeA创建文档,并且_id生成的东西在DocTypeA文档中保存为_id。但是,当我在创建DocTypeA文档时尝试引用DocTypeB文档id时,我会得到强制转换错误(在标题中提到)。
下面是创建DocTypeA的代码
const create = async (payload) => {
const docA = new DocTypeA(payload)
await docA.save()
return docA
}对于创建DocTypeB,我使用:
const create = async (payload) => {
const docB = new DocTypeB(payload)
await docB.save()
return docB
}发布于 2020-12-07 08:14:52
ULID不是合格的ObjectId。它们不是十六进制字符串,而是26字符长度标识符.
考虑到DocTypeB的模式声明方式,docA字段应该是String类型,而不是ObjectId类型。
DocTypeB的模式定义应该如下所示。
const schema = new Schema({
_id: { type: Schema.Types.String, default: () => ULID.ulid(Date.now()) },
name: { type: Schema.Types.String },
docA: { type: Schema.Types.String, ref: 'DocTypeA' },
});否则,猫鼬将尝试将标识符转换为ObjectId,这将引发。
async function create() {
const docA = new DocTypeA({name: 'Jack'})
await docA.save()
const docB = new DocTypeB(
{name: 'Jill', docA} // Or {name: 'Jill', docA: docA._id})
)
await docB.save();
}
create().then(console.log('done')).catch(console.error)注意,是为集合中的_id field自动添加的唯一索引,所以您必须小心,不要在不同的文档中为它设置相同的值。
https://stackoverflow.com/questions/65012612
复制相似问题