【问题标题】:How to change the object which find or save from mongodb如何更改从 mongodb 中查找或保存的对象
【发布时间】:2018-08-21 07:01:19
【问题描述】:

这是我的帐户架构:

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

然后我想更改查找数据:

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

结果:

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

所以我该怎么做才能得到这个结果:

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

也许我可以分配给一个新对象,但如果我的架构有很多属性?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我不相信您可以以这种方式直接编辑从find 操作收到的记录。相反,您可以使用findAndModify

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

    您可以找到文档here

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多