需要在异步查找操作中修改 json 和 return
Need to modify json and return inside aync find operation
我需要通过一个对象 ID 列表,找到一个用户,然后修改 json 对象和 return 它。
我调查了 bluebird,但下面的代码没有按照我的意愿执行。似乎修改 json 对象是在 returning 之后完成的。
我已经尝试 return user["test"] = "lol"
但只有 return 是 "test" 的值,而我需要整个更新的 json。
Promise.map(['5781635026d6fad4486d81e9', '578296e31029e27b4ea53e9d'], function(i) {
return User.findOneAsync({
_id: i
}).then(function(user) {
user["test"] = "lol";
return user;
});
}).then(function(array) {
res.send(array);
})
有什么优雅的解决方法吗?
您可以采取的一种简单方法是使用 $in
operator with the array of ids in your query, then apply the lean()
method to return plain JS objects as Mongoose documents 不允许添加属性。
看看这个例子:
User.find({ "_id": { "$in": ['5781635026d6fad4486d81e9', '578296e31029e27b4ea53e9d'] } })
.lean()
.exec()
.then(function(docs) {
var users = docs.map(function(user) {
user["test"] = "lol";
return user;
});
res.send(users);
})
我需要通过一个对象 ID 列表,找到一个用户,然后修改 json 对象和 return 它。
我调查了 bluebird,但下面的代码没有按照我的意愿执行。似乎修改 json 对象是在 returning 之后完成的。
我已经尝试 return user["test"] = "lol"
但只有 return 是 "test" 的值,而我需要整个更新的 json。
Promise.map(['5781635026d6fad4486d81e9', '578296e31029e27b4ea53e9d'], function(i) {
return User.findOneAsync({
_id: i
}).then(function(user) {
user["test"] = "lol";
return user;
});
}).then(function(array) {
res.send(array);
})
有什么优雅的解决方法吗?
您可以采取的一种简单方法是使用 $in
operator with the array of ids in your query, then apply the lean()
method to return plain JS objects as Mongoose documents 不允许添加属性。
看看这个例子:
User.find({ "_id": { "$in": ['5781635026d6fad4486d81e9', '578296e31029e27b4ea53e9d'] } })
.lean()
.exec()
.then(function(docs) {
var users = docs.map(function(user) {
user["test"] = "lol";
return user;
});
res.send(users);
})