【问题标题】:Update Results From MongoDB Before emmiting在发出之前从 MongoDB 更新结果
【发布时间】:2016-10-19 10:36:32
【问题描述】:

假设我有这个查询

var query1 = usersrec.find({username:target}, {});
query1.exec(function (err, docs){
    if(err) throw ;
});

它给出了这个结果

{ 
    "_id" : ObjectId("5806ba413202e30d68152aa4"), 
    "username" : "sammy", 
    "firstname" : "samuel", 
    "lastname" : "jackson", 
    "gender" : "male", 
    "phone" : "0123456789", 
    "image" : "sam.jpg"
}

我想在使用 socket.io 发出之前,将从另一个集合 {"Balance" : "1011"} 获得的值添加到这个结果文档中。

我已经尝试了很多事情并得到了错误,但这没有添加余额键/值:

docs[0].balance = '1011';
console.log(docs);
socket.emit('usernames', docs);

文档仍保留其初始值。我错过了什么?

【问题讨论】:

  • 似乎您正在使用 Mongoose,如果是这样,那么您需要在查询 query1.lean().exec(...) 上调用 lean() 方法。这将确保从启用了精简选项的查询返回的文档是纯 JavaScript 对象,您可以对其进行操作并添加其他 balance 属性。
  • @chridam 非常感谢!像魅力一样工作。有趣的是,您不知道的微小事物可以使代码完全不同。谢谢!

标签: mongodb mongoose socket.io


【解决方案1】:

似乎您正在使用 Mongoose 和 Mongoose documents 不允许添加属性。您需要在 exec() 之前调用 lean() 方法,因为启用了精简选项的查询返回的文档是纯 javascript 对象:

来自文档:

var query1 = usersrec.find({username:target}, {});
query1.lean().exec(function (err, docs) {
    docs[0] instanceof mongoose.Document // false
});

所以你的代码应该是这样的:

var query1 = usersrec.find({username:target}, {});
query1.lean().exec(function (err, docs){
    if(err) throw ;
    docs[0].balance = '1011';
    console.log(docs);
    socket.emit('usernames', docs);
});

或将返回的文档转换为普通对象:

var query1 = usersrec.find({username:target}, {});
query1.exec(function (err, docs){
    if(err) throw ;
    docs = docs.map(function(o){ return o.toObject(); });
    docs[0].balance = '1011';
    console.log(docs);
    socket.emit('usernames', docs);
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-05-13
  • 2018-04-30
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多