【问题标题】:using custom _id in mongodb, and linking to another object在 mongodb 中使用自定义 _id,并链接到另一个对象
【发布时间】:2018-04-10 04:59:33
【问题描述】:

我正在尝试为 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: 'StackOverflow',
    _id: 'stack.com' //unique
});
group.save();

到这里一切正常。现在我必须将组链接到用户。

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

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

谢谢。

【问题讨论】:

  • User 中的这个错误:Groups: { type: [ObjectId], default: [] }。您似乎在尝试“引用”模式。您将Group 中的_id 定义为“字符串”,因此您的“参考”列表需要是“相同类型”,并且也表示为“参考”Groups: [{ type: ObjectId, ref: 'Group' }]。这实际上在Mongoose Schemas 中有详细说明。 default: [] 也没有效果。在模式中定义数组元素时,如果您不提供元素,则会得到一个空数组。

标签: node.js mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

在你的 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。我不认为它会起作用。如果你想让一个字段唯一,你可以尝试其他名称。

【讨论】:

  • 如何将新的推送到用户模型的组字段中?保存时... user.Groups.push(groupId); // 或 user.G.push(mongoose.Types.ObjectId(_g)); user.save();
  • 我想我明白了...组:[{ type: Schema.Types.ObjectId, ref: 'groups'}] 应该是组:[{ type: 'String', ref: ' groups'}] ... 因为组 ID 是 String 而不是 ObjectId
  • 我认为你应该保留类型:Schema.Types.ObjectId。要推送新组,您可以执行 User.findByIdAndUpdate(yourUserId, { $push: { groups: yourNewGroup } }) 之类的操作。它也有效
猜你喜欢
  • 2016-12-15
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2017-05-06
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
相关资源
最近更新 更多