javascript - 如何使用对象 ID 数组创建 Mongoose 模式?

我已经定义了一个 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 的数组。我不确定这是否是这样做的正确符号。

我正在尝试将一个新 friend 推送到当前用户的 friend 数组中:

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 填充功能,你应该这样做:

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(...)

您会看到每个用户都有一组用户(该用户的 friend )。

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

user.friends.push(newFriend._id);

https://stackoverflow.com/questions/22244421/

相关文章:

mongodb - mongoDB中的字符串字段值长度

mongodb - 检查 MongoDB upsert 是否进行了插入或更新

mongodb - MongoDB stats() 函数是否返回位或字节?

mongodb - 在 MongoDB 中传递给 $in 查询的最大参数数是多少?

mongodb - 如何在 Mongoose 中进行原始 mongodb 操作?

python - 如何从 pymongo 发出 "show dbs"

c# - .NET MongoDB 连接的最佳实践?

mongodb - 如何按插入时间对 Meteor 集合进行排序?

sql - MongoDB如何避免SQL注入(inject)困惑?

MongoDB 通过 Mongoose JS - findByID 是什么?