在 mongodb 中使用自定义 _id,并链接到另一个对象

using custom _id in mongodb, and linking to another object

我正在尝试为 mongodb 个对象使用自定义 _id。

我有两个对象:用户和组

用户:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const ObjectId = Schema.Types.ObjectId;

const userSchema = new Schema(
    {
        //Username
        _id: {
            type: String,
            unique: true
        },

        name: {
            type: String,
            required: 'Name is required.'
        },

        //Groups [ group-unique-url ]
        Groups: {
            type: [ObjectId],
            default: []
        }
    },
    { _id: false }
);

mongoose.model('users', userSchema);

群组:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const groupSchema = new Schema(
    {
        //unique URL
        _id: {
            type: String,
            unique: true
        },

        //Name of the Group
        name: {
            type: String,
            unique: true,
            required: true
        }
    },
    { _id: false }
);

mongoose.model('groups', groupSchema);

保存用户:

const user = new User({
    name: 'Surya Chandra',
    _id: 'surya'
});
user.save();

保存组:

const group = new Group({
    name: 'Whosebug',
    _id: 'stack.com' //unique
});
group.save();

到目前为止一切正常。现在我要 link 组给用户。

userId => 'surya' & groupId => 'stack.com'

const user = await User.findById(userId); //'surya'

if (user.Groups.indexOf(groupId) >= 0) {
} else {
    user.Groups.push(groupId); //user.G.push(mongoose.Types.ObjectId(_g));
    user.save();
}

user.Groups.push(groupId)

CastError: Cast to ObjectId failed for value "stack.com" at path "Groups"

user.Groups.push(mongoose.Types.ObjectId(_g));

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

我不确定如何将组添加到用户组。如何查询特定组中的所有用户?此外,这是否支持从“用户组”字段填充组名?

谢谢。

在你的 userSchema 中,你应该这样做

const userSchema = new Schema(
{
    //Username
    _id: {
        type: String,
        unique: true
    },

    name: {
        type: String,
        required: 'Name is required.'
    },

    groups: [{ type: Schema.Types.ObjectId, ref: 'groups'}]
},
);

ref: 'groups' 必须与您在组模型中定义的模型名称相匹配

mongoose.model('groups', groupSchema);

稍后要查找组,您可以使用 populate('groups')。阅读猫鼬文档以获取更多详细信息 我也不明白你为什么要覆盖猫鼬的 _id。我不认为它会工作。如果你想让一个字段唯一,你可以尝试其他名称。