我使用mongoose从mongo获取一个对象,但我想使用lean,因为mongoose模型中没有属性(strict:false) 修改该对象后,我无法将其保存回来
let order = await Order.findOne({_id: req.body.id}).populate({path: 'o_s', match: {removed: false}}).lean()
order.save() //not working as it's not mongoose model any more
Order.update({_id:order._id},{order}).exec(function(){
return res.json({status: true, message: 'Order Updated', order: order});
}) //not giving error but not updating too
有什么建议吗?
答案 0 :(得分:0)
要更新从数据库中检索的文档,您必须删除_id属性。
考虑这个人为的例子:
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schema = new Schema({
name: String
});
schema.set('strict', false);
const Test = mongoose.model('test', schema);
const test = new Test({
name: 'Henry',
nick: 'Billy'
});
async function run() {
await conn.dropDatabase();
await test.save();
let doc = await Test.findOne({}).lean();
const id = doc._id;
delete doc._id;
doc.name = 'Billy';
doc.nick = 'The Kid';
await Test.update({ _id: id }, doc);
let updated = await Test.findOne({});
console.log(updated);
return conn.close();
}
run();
<强>输出:强>
{ _id: 5ad34679bc95f172c26f3382,
name: 'Billy',
nick: 'The Kid',
__v: 0 }
请注意,在这种情况下您会丢失自动版本控制,如果这对您很重要,则需要手动增加版本属性。