如何使用对象 ID 数组创建猫鼬模式?

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

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’

118753 次浏览

I would try this.

user.friends.push(newFriend._id);

or

friends: [userSchema],

but i'm not sure if this is correct.

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

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.