0

this is my account schema:

const account = new mongoose.Schema({
    name: String,
    age: Number,
    coins: Number,
    phone: Number,
    sex: {
        type: String,
        default: 'f'
    }
}, {
        timestamps: {
            createdAt: 'created_at',
            updatedAt: 'updated_at'
        }
    }
)

then I want to change the find data:

Account.find({age: {$eq: 20}}, function(err, data) {
    console.log(err, data);
    data[0].testword = 'hello'; //can`t add element
    data[0].age = 'world'; //can`t change num to string
    console.log(data)
})

result:

[ { _id: 5a97667011998b05027b9e62,
    name: 'bob',
    age: 20,
    sex: 'f' }]
[ { _id: 5a97667011998b05027b9e62,
    name: 'bob',
    age: 20,
    sex: 'f' }]

so How can should I do to get this result:

 [ { _id: 5a97667011998b05027b9e62,
        name: 'bob',
        age: 'world',   //change type
        testword: 'hello', //add an attribute
        sex: 'f' }]

and maybe I can assignment to a new object, but if my schema has many attributes?

Borkes
  • 181
  • 1
  • 2
  • 11

1 Answers1

0

I do not believe you can directly edit the record received from the find operation in that way. Instead, you could use findAndModify.

Account.findAndModify(
  {age: {$eq: 20}},
  {$set: {testword: 'hello'}}, 
  function(err, data){
    console.log(err, data);
  }
);

You can find the docs here.

Deem
  • 7,007
  • 2
  • 19
  • 23
  • I don`t want to change db using modify, and I find a way to solve my problem. ```Account.find({}).lean().then() ```, what I need is ```lean()``` . – Borkes Mar 13 '18 at 06:29
  • https://stackoverflow.com/questions/9952649/convert-mongoose-docs-to-json – Borkes Mar 13 '18 at 06:32