How To Create Mongoose Schema with Array of Object IDs?

后端 未结 3 1289
青春惊慌失措
青春惊慌失措 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: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);
    

提交回复
热议问题