-1

I am a newer in meanjs. Now I am stuck in how to manipulate the data queried from mongodb using mongoose. Here is my case:

Model schema is this:

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
}

});

When I try to get data and manipulate with following code:

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

The result shows as follow, it just doesn't work.

2015-04-07

Tue Apr 07 2015 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'
}

I have tried to manipulate with like this: users[1]['created'] = created;

or using set function: users[1].set('created', created);

both failed. Please give a hand.

Any help would be appreciated.

Neo-coder
  • 7,715
  • 4
  • 33
  • 52
deko
  • 350
  • 4
  • 15
  • In this case, I just want to get it to front-end and show the created date like "2015-04-07" instead of like "Tue Apr 07 2015 12:00:00 GMT+1200 (NZST)". But the purpose of this question is that how to manipulate the data got from mongodb, as result shown in console.log, the data users[1].created cannot be changed in my way. – deko Apr 07 '15 at 04:49
  • Got the answer from http://stackoverflow.com/questions/15670792/is-mongoose-query-result-read-only?rq=1, use toObject() to get a writable copy or use lean(true) (true is default even without true) to make result of the query to be a plain json object instead of mongoose document. I use lean() to fix this case, however, tried both and both works – deko Apr 07 '15 at 12:16
  • Can I know why this gets a downvote? – deko Aug 23 '19 at 17:44

1 Answers1

0

EDIT

you can define getters in your schema.

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

Are you saying you want to get the AdminUser model from the database, modify it, then save it back to the database?

lyjackal
  • 3,984
  • 1
  • 12
  • 25
  • Hi @lyjackal, I don't want to save it back to database, In this case, I just want to get it to front-end and show the created date like "2015-04-07" instead of like "Tue Apr 07 2015 12:00:00 GMT+1200 (NZST)". – deko Apr 07 '15 at 04:47
  • did that answer your question? – lyjackal Apr 07 '15 at 05:26
  • Thanks @lyjackal, using your way. console.log(users[1].created) returns the formatted value which is "2015-04-07". But when output console.log(users[1]), it still shows no difference. As I'm trying return the entire object to front-end by res.json(users[1]), it still doesn't quite meet. Do I need to create a new object and copy properties then return new object to front-end? It's quite unconvenient. – deko Apr 07 '15 at 11:06
  • Got answer from here http://stackoverflow.com/questions/15670792/is-mongoose-query-result-read-only?rq=1, use toObject() or lean(). – deko Apr 07 '15 at 12:16
  • Use toJSON(), instead of toObject() to format date as string – lyjackal Apr 07 '15 at 12:18