如何用对象ID数组创buildMongoose模式?

我已经定义了一个mongoose用户模式:

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

friends参数被定义为对象ID数组。 换句话说,用户将拥有包含其他用户的ID的数组。 我不确定这是否是这样做的正确标记。

我正尝试将一个新的朋友推送给当前用户的朋友数组:

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

但是这给了我以下错误:

TypeError:对象531975a04179b4200064daf0没有方法'cast'

如果你想使用Mongoose填充function,你应该这样做:

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

这样你可以做这个查询:

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

你会看到每个用户将有一个用户数组(这个用户的朋友)。

正确的插入方式就像Gabor所说:

 user.friends.push(newFriend._id); 

我会试试这个。

 user.friends.push(newFriend._id); 

要么

 friends: [userSchema], 

但我不确定这是否正确。