我是meanjs的新手。现在我陷入了如何使用mongoose操纵从mongodb查询的数据。这是我的情况:
模型架构是这样的:
var AdminUserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
},
email: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your email'],
match: [/.+\@.+\..+/, 'Please fill a valid email address']
},
username: {
type: String,
unique: 'Username already exists',
required: 'Please fill in a username',
trim: true
},
password: {
type: String,
default: '',
validate: [validateLocalStrategyPassword, 'Password should be longer']
},
salt: {
type: String
},
provider: {
type: String,
required: 'Provider is required'
},
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['admin']
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
},
enabled: {
type: Boolean,
default: true
}
});
当我尝试获取数据并使用以下代码进行操作时:
var AdminUser = mongoose.model('AdminUser');
AdminUser.find().exec(function(err, users) {
if(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
users[1].password = undefined;
users[1].salt = undefined;
var created = moment(users[1].created).format('YYYY-MM-DD');
users[1].created = created;
console.log(created);
console.log(users[1].created);
console.log(users[1]);
}
});
结果显示如下,它不起作用。
2015年4月7日
2015年4月7日星期二12:00:00 GMT + 1200(NZST)
{
_id: 55233e0c488bd50b1eafe558,
salt: undefined,
displayName: 'testtest',
provider: 'local',
username: 'test',
__v: 0,
enabled: true,
created: TueApr07201512: 00: 00GMT+1200(NZST),
roles: [
'admin'
],
password: undefined,
email: 'test@test.com',
lastName: 'test',
firstName: 'test'
}
我试图像这样操纵:
users[1]['created'] = created;
或使用set功能:
users[1].set('created', created);
任何帮助都将不胜感激。
答案 0 :(得分:0)
修改强>
您可以在架构中定义getter。
created: {
type: Date,
default: Date.now,
get: function(date) {
// return a formatted string instead of the Date object
return moment(date).format('YYYY-MM-DD');
}
}
您是说要从数据库中获取AdminUser
模型,修改它,然后将其保存回数据库?