问题描述
我已经定义了一个猫鼬用户架构:
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);
friends 参数被定义为一个对象 ID 数组.换句话说,一个用户将拥有一个包含其他用户 ID 的数组.我不确定这是否是执行此操作的正确符号.
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:
类型错误:对象 531975a04179b4200064daf0 没有方法 'cast'
TypeError: Object 531975a04179b4200064daf0 has no method 'cast'
推荐答案
如果你想使用 Mongoose 填充功能,你应该这样做:
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(...)
您将看到每个 User 将拥有一组用户(该用户的朋友).
You'll see that each User will have an array of Users (this user's friends).
正确的插入方式就像 Gabor 说的:
And the correct way to insert is like Gabor said:
user.friends.push(newFriend._id);
这篇关于如何使用对象 ID 数组创建猫鼬模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!