【问题标题】:How to update only some properties of object in MongoDB database with Arrays如何使用数组仅更新 MongoDB 数据库中对象的某些属性
【发布时间】:2018-10-06 05:25:41
【问题描述】:

这与这个问题基本相同...StackOverflow Question ...但我需要知道数组周围的行为。

我遇到 $set 仍在更新其他变量的问题。这是我的查询,它正在更新这些变量,但它也设置了一些数组(媒体:[] 和运动:[])我在运动员档案中.0 回空。

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

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

我做错了什么?

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

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

    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 (err) return handleError(err);

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

    【讨论】:

    • 抱歉不清楚。运动员Profile 是一个数组,这就是为什么我使用运动员Profile.0 进入第一个对象并更改第一个对象的原因。
    • 好的,你想更新 atheleteprofile 的第一个对象吗?
    • @ash 我刚刚更新了答案,请仔细阅读,如果有帮助别忘了放弃投票
    • 谢谢!这样可行。我试图投票,但我的声誉太低了。希望对您有所帮助。
    • @ash 如果这个答案对你有帮助,那么你可以用勾号标记这个 amswer 以使其回答
    猜你喜欢
    • 2018-01-14
    • 2019-04-28
    • 2020-08-14
    • 1970-01-01
    • 2019-06-22
    • 2019-05-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多