Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - How To Create Mongoose Schema with Array of Object IDs?

I have defined a mongoose user schema:

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: [mongoose.Types.ObjectId],
  accessToken: { type: String } // Used for Remember Me
});

var listSchema = new mongoose.Schema({
    name: String,
    description: String,
    contents: [contentSchema],
    created: {type: Date, default:Date.now}
});
var contentSchema = new mongoose.Schema({
    name: String,
    quantity: String,
    complete: Boolean
});

exports.User = mongoose.model('User', userSchema);

the friends parameter is defined as an array of Object IDs. So in other words, a user will have an array containing the IDs of other users. I am not sure if this is the proper notation for doing this.

I am trying to push a new Friend to the friend array of the current user:

user = req.user;
  console.log("adding friend to db");
  models.User.findOne({'email': req.params.email}, '_id', function(err, newFriend){
    models.User.findOne({'_id': user._id}, function(err, user){
      if (err) { return next(err); }
      user.friends.push(newFriend);
    });
  });

however this gives me the following error:

TypeError: Object 531975a04179b4200064daf0 has no method 'cast'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...