如何使用Arrays仅更新MongoDB数据库中对象的某些属性

时间:2018-04-25 16:36:46

标签: javascript node.js express mongoose

这与这个问题基本上是同一个问题... StackOverflow Question ...但我需要了解数组周围的行为。

我遇到了$ set仍然更新其他变量的问题。这是我的查询,它正在努力更新这些变量,但它也设置了一些数组(media:[]和sports:[])我在AthleProfile中.0回到空。

为了清楚起见,这里是用户对象的Schema。

UserSchema.js

const UserSchema = new Schema({
 password: { type: String, required: true },
 username: { type: String, unique: true, required: true },
 role: { type: String, required: true },
 athleteProfile: [AthleteSchema],
 evaluatorProfile: [EvaluatorSchema],
 adminProfile: [AdminSchema],
 search: [SearchSchema]
});

AthleteSchema.js

const AthleteSchema = new Schema({
 athEmail: String,
 firstName: {
   type: String,
   validate: {
     validator: (firstName) => firstName.length > 2,
     message: 'Name must be longer than 2 characters.'
   }
 },
 lastName: {
   type: String,
   validate: {
     validator: (lastName) => lastName.length > 2,
     message: 'Name must be longer than 2 characters.'
   }
 },
 profilePic: String,
 accountType: String,
 events: [{
   ref: 'Events',
   type: Schema.Types.ObjectId
 }],
 media: [MediaSchema],
 city: String,
 state: String,
 zip: Number,
 country: { type: String, uppercase: true },
 height: String,
 weight: Number,
 birthday: Date,
 sports: {
  type: [SportSchema],
   validate: [arrayLimit, '{PATH} exceeds the limit of 3']
 },
 references: {
   type: [ReferenceSchema],
   validate: [arrayLimit, '{PATH} exceeds the limit of 3']
 },
 evaluations: [EvaluationSchema],
 gradYear: Number,
 school: String
});

然后这是请求。

  User.findByIdAndUpdate({ _id: id }, {
   $set:
  { username,
    password,
     'athleteProfile.0': {
      firstName,
      lastName,
      athEmail: email,
      gradYear,
      school,
      birthday,
      city,
      state,
      zip,
      weight,
      height
  }}
}, { returnNewDocument: true});

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你的问题很清楚你想要更新哪个字段,所以我理解的是 您可以使用以下代码:

User.findById(id, function (err, user) {

  if (err) return handleError(err);

  user.keytochange = newvalue;

  user.save(function (err, updatedUser) {


    if (err) return handleError(err);

    res.send(updatedUser);

  });
}) 

从我明白你想要更新的问题 athleteProfile为0,因此相应更改

在更新的问题后编辑答案 因此,在看到问题后,您尝试做的是更新当前用户的atheleprofile基础,因此我建议您不要将who模式传递给atheletprofile,而是将带有ref的objectid传递给用户类似的东西

title: String, Atheleprofile: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },  现在依次映射它,所以当你想添加用户时,将用户的objectId给予atheleprofile然后更新功能 这样做

User.findById(id,function(err,user){       if(错误)返回handleError(错误);

  Atheleprofile.findById(user.id , (err,atheleprofile) => {
           Atheleprofile.fieldnam = newvalue;
          Athelerpofile.save((err,newAtheleprofileObejct) =>{
             console.log("done changes");
       }
     }



  });
}) `