How To Create Mongoose Schema with Array of Object IDs?

后端 未结 3 1288
青春惊慌失措
青春惊慌失措 2020-12-07 14:15

I have defined a mongoose user schema:

var userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true},
  password: { type: String,         


        
相关标签:
3条回答
  • 2020-12-07 14:36

    I'm new to Mongoose myself, so I'm not entirely sure this is right. However, you appear to have written:

    friends: [mongoose.Types.ObjectId],
    

    I believe the property you're looking for is actually found here:

    friends: [mongoose.Schema.Types.ObjectId],
    

    It may be that the docs have changed since you posted this question though. Apologies if that's the case. Please see the Mongoose SchemaTypes docs for more info and examples.

    0 讨论(0)
  • 2020-12-07 14:48

    I would try this.

    user.friends.push(newFriend._id);
    

    or

    friends: [userSchema],
    

    but i'm not sure if this is correct.

    0 讨论(0)
  • 2020-12-07 14:49

    If you want to use Mongoose populate feature, you should do:

    var userSchema = mongoose.Schema({
      email: { type: String, required: true, unique: true},
      password: { type: String, required: true},
      name: {
          first: { type: String, required: true, trim: true},
          last: { type: String, required: true, trim: true}
      },
      phone: Number,
      lists: [listSchema],
      friends: [{ type : ObjectId, ref: 'User' }],
      accessToken: { type: String } // Used for Remember Me
    });
    exports.User = mongoose.model('User', userSchema);
    

    This way you can do this query:

    var User = schemas.User;
    User
     .find()
     .populate('friends')
     .exec(...)
    

    You'll see that each User will have an array of Users (this user's friends).

    And the correct way to insert is like Gabor said:

    user.friends.push(newFriend._id);
    
    0 讨论(0)
提交回复
热议问题