gpt4 book ai didi

javascript - 迭代集合对象 MongoDB 时如何使用 forEach?

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:56 25 4
gpt4 key购买 nike

请建议我如何从数据库中进行选择,将集合中的 ID 与数组的每个元素进行比较?不幸的是,下面的代码返回了一个空数组:

index(req, res) {
Room.find({_id: req.user.rooms.forEach((item)=>{
return item;
})
})
.then((rooms) => {
console.log(rooms)
res.send(rooms)
}
)
.catch(err => res.status(400).json(err));
}

req.user.rooms - 该数组的每个项目都是 ID,我想将其与集合 Room 中的内容进行比较。

最佳答案

他们的文档中非常简单地介绍了如何 query items in a list .

您的代码应如下所示:

index(req, res) {
// Additional validation should be done to make sure that req.user.rooms
// is an array with length > 0. I'll leave that for you to do.
const rooms = req.user.rooms;

Room.find({ _id: rooms})
.then((rooms) => {
console.log(rooms)
res.send(rooms)
})
.catch(err => res.status(400).json(err));
}
<小时/>

除此之外,您实际上不应该从 Controller 执行数据库查询; it's not a good architectural practice这就是它在 Node 服务中的样子

roomController.js

const RoomService = require("/path/to/services/directory"); // Let services contain all business logic. Don't give them anything related to your web server framework

async index(req, res) {
// Additional validation should be done to make sure that req.user.rooms
// is an array with length > 0. I'll leave that for you to do.
try {
const rooms = await RoomService.retrieveById(req.user.rooms);
res.send( { success: true, data: rooms } ); // We send back the result when we get one
} catch ( err ) {
// We respond to the client with our error, ideally you'll log it too
res.status( err.statusCode ).send( { success: false, error: err } );
}

}

RoomService.js

const Room = require("/path/to/your/model");

module.exports = {
retrieveById: async function(ids) {
try {
return await Room.find({ _id: ids}); // Typically this would be abstracted to a DB layer. but putting it here for brevity
} catch( err ) {
throw new Error( err ); // This is caught in our controller, which we send to client
}

}
};

关于javascript - 迭代集合对象 MongoDB 时如何使用 forEach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60065665/

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