更新mongoose模式中的未定义属性并保存

时间:2015-01-25 03:52:46

标签: node.js mongodb mongoose

我已定义了如下所示的用户架构

var UserSchema = new Schema({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  email: { type: String, required: true },
  location: String,
  picture: String,
  isFirstNamePublic: { type: Boolean, required: false, Default: false },
  isLastNamePublic: { type: Boolean, required: false, Default: false },
  isEmailPublic: { type: Boolean, required: false, Default: false },
  isLocationPublic: { type: Boolean, required: false, Default: false },
  isPicturePublic: { type: Boolean, required: false, Default: false },
  passwordHash: { type: String, required: true },
  userRoles: [{businessId: String, role: {type: String, uppercase: true, enum: ['INDIVIDUAL_USER', 'BUSINESS_EMPLOYEE', 'BUSINESS_ADMIN', 'CLIENT', 'PLATFORM_EMPLOYEE']}}],
  interestedOfferCategory: String,
  linkedSocialNetwork: {type: String, required: false, uppercase: true, enum: ['FACEBOOK', 'TWITTER', 'LINKEDIN']},
  linkedSocialNetworkUserId: String,
  resetPasswordToken: String,
  resetPasswordExpired: Boolean
});

现在如果我想更新任何未定义的字段,我无法更新。例如:我有一个用户文档保存如下

{ _id: 54c439395ff4ede519912ea8,
  firstName: 'updated first name',
  lastName: 'test',
  email: 'test@test.com',
  interestedOfferCategory: 'testcategory',
  passwordHash: '$2a$10$S1zqmQHQ7Sd/qJjtryfzFua4Rn6Xi/oCHsJP9mLfyUnMg/gNV/u3K',
  __v: 0,
  userRoles: 
   [ { businessId: '123',
       role: 'INDIVIDUAL_USER',
       _id: 54c439395ff4ede519912ea9 } ] }

现在我将此文档扩展为添加resetPasswordToken,如下所示

var updatedUser = _.extend(user, {resetPasswordToken: token, revokeSessionTokenExpired: false});

如果我尝试保存文档,则不会更新resetPasswordToken和resetPasswordTokenExpired的值。

updatedUser.save(cb);

上述行未更新值。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

对象'用户'正在扩展的看起来是一个猫鼬模型对象,它使用' new'进行实例化。关键词。如果这是真的,你必须调用do var objUser = user.toObject()并扩展objUser。

  var mongooseUser = require('/path/mongooseUserSchemaFileName.js');

  var userDoc = { 
                    _id: 54c439395ff4ede519912ea8,
                    firstName: 'updated first name',
                    lastName: 'test',
                    email: 'test@test.com',
                    interestedOfferCategory: 'testcategory',
                    passwordHash: '$2a$10$S1zqmQHQ7Sd/qJjtryfzFua4Rn6Xi/oCHsJP9mLfyUnMg/gNV/u3K',
                    __v: 0,
                    userRoles: [ 
                          { businessId: '123',
                            role: 'INDIVIDUAL_USER',
                            _id: 54c439395ff4ede519912ea9 
                          } 
                               ] 
                    }

   var tempUser = _.extend(userDoc, {resetPasswordToken: token,     revokeSessionTokenExpired: false});

   var updateUser = new mongooseUser(tempUser);
   updatedUser.save(cb);