如何创建具有对象ID数组的Mongoose架构? [英] How To Create Mongoose Schema with Array of Object IDs?
问题描述
我已经定义了一个mongoose用户模式:
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:
TypeError:Object 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);
这样可以这样查询:
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).
正确的插入方式就像Gabor说:
And the correct way to insert is like Gabor said:
user.friends.push(newFriend._id);
这篇关于如何创建具有对象ID数组的Mongoose架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!