How To Create Mongoose Schema with Array of Object IDs?

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);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)