2017-10-28 91 views
0

我正在尝试为mongodb对象使用自定义_id。在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(); 

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

用户id => '苏里亚' &的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));我不确定如何将用户组添加到组。如何查询特定组中的所有用户?另外,这是否支持从用户组字段填充组名?

谢谢。

+1

This'in User'is wrong:'Groups:{type:[ObjectId],default:[]}'。您似乎尝试一个“引用”模式。您在'Group'内定义了'_id'作为“string”,因此您的“reference”列表需要是“相同类型”,并且表示为“ref”,Groups:[{type:ObjectId,ref: '组'}]'。这实际上全部在[Mongoose Schemas](http://mongoosejs.com/docs/guide.html)中详述。另外'default:[]'不起作用。在模式中定义数组元素时,如果您不提供元素,则会得到一个空数组。 –

回答

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'}] 
}, 
); 

裁判:“群体”必须

mongoose.model('groups', groupSchema); 

的找到你在你的团队模型中定义的模型名称相匹配之后,您可以使用填充('组')。阅读猫鼬的文档更详细 我也不明白你为什么要重写_id猫鼬。我不认为它会起作用。如果您想让某个字段具有唯一性,您可以尝试其他名称。

+0

如何推送用户模型的新组内字段?同时保存... user.Groups.push(groupId); //或user.G.push(mongoose.Types.ObjectId(_g)); user.save(); –

+0

我想我明白了... 组:[{类型:Schema.Types.ObjectId,REF: '群体'}] 应该 组:[{类型: '字符串',裁判: '群体' }] ...作为组ID是String而不是ObjectId –

+0

我认为你应该保持类型:Schema.Types.ObjectId。要推新群组,你可以做一些像User.findByIdAndUpdate(yourUserId,{$ push:{groups:yourNewGroup}})。它也可以工作 – dnp1204

相关问题