gpt4 book ai didi

node.js - 链接 Mongoose 查询的最佳方式

转载 作者:IT老高 更新时间:2023-10-28 13:32:31 26 4
gpt4 key购买 nike

我是一名使用 node 和 mongoose 的新手开发人员,想知道用 mongoose 链接查询的最佳方式是什么。我正在像下面那样做,它不起作用。

User.findByIdAndUpdate(req.params._id, user, { upsert: true })
.exec((err, updatedUser) => {
if (addedCollections) {
return User.findByIdAndUpdate(req.params._id, { $push: { _collections: { $each: addedCollections } } }, { upsert: true }).exec();
}
return new Query;
})
.exec(() => {
return User.findById(req.params._id).populate('_collections');
})
.exec((err, user) => {
res.json({ user });
})

如何链接多个查询?

最佳答案

您可以使用 Promise 链,它看起来与您尝试执行的操作非常相似:

User.findByIdAndUpdate(req.params._id, user, { upsert: true })
.then(updatedUser => {
if (addedCollections) {
return User.findByIdAndUpdate(req.params._id, { $push: { _collections: { $each: addedCollections } } }, { upsert: true });
}
})
.then(() => {
return User.findById(req.params._id).populate('_collections');
})
.then(user => {
res.json({ user });
})
.catch(err => {
res.status(500).json({ error : err });
});

关于node.js - 链接 Mongoose 查询的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38439748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com