IT Share you

객체 ID 배열로 몽구스 스키마를 만드는 방법은 무엇입니까?

shareyou 2020. 11. 30. 20:15
반응형

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

그러나 이것은 다음과 같은 오류를 제공합니다.

유형 오류 : 개체 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(...)

각 사용자는 사용자 (이 사용자의 친구) 배열을 갖게됩니다.

삽입하는 올바른 방법은 Gabor가 말한 것과 같습니다.

user.friends.push(newFriend._id);

저는 Mongoose를 처음 사용하므로 이것이 옳은지 완전히 확신하지 못합니다. 그러나 다음과 같이 작성한 것으로 보입니다.

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.


I would try this.

user.friends.push(newFriend._id);

or

friends: [userSchema],

but i'm not sure if this is correct.

참고URL : https://stackoverflow.com/questions/22244421/how-to-create-mongoose-schema-with-array-of-object-ids

반응형