gpt4 book ai didi

node.js - 如何编写给定 mongodb 查询的 mongoose 函数?

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

这是选择包含 user1 和 user2 的房间文档的查询。

db.getCollection("rooms").find({
$and:[
{users: ObjectId("5e2916615f55cc6e3cb9838b")},
{users: ObjectId("5e2b51107d1c624260620e9e")}
]
})

它在 mongodb shell 中运行良好并返回以下文档。

{ 
"_id" : ObjectId("5e55ae0e07f8bf48dc602d1c"),
"users" : [
ObjectId("5e2916615f55cc6e3cb9838b"),
ObjectId("5e2b51107d1c624260620e9e")
],
"label" : "",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("5e55ae98bec6265a48d453e6"),
"users" : [
ObjectId("5e2916615f55cc6e3cb9838b"),
ObjectId("5e2b51107d1c624260620e9e")
],
"label" : "",
"__v" : NumberInt(0)
}

我想在带有 mongoose 的 Nodejs 中使用此查询。

import { Schema, model } from "mongoose";
import mongodb from "mongodb";

const RoomSchema = new Schema({
users: [
{
type: Schema.Types.ObjectId,
ref: "User",
required: true,
autopopulate: { select: "name phone photo" }
}
],
label: { type: String, text: true }
});

export default model("Room", RoomSchema);
... ... ...
const filter = {
$and: [
{ users: new mongodb.ObjectID(uid1) },
{ users: new mongodb.ObjectID(uid2) }
]
};
const items = Room.find(filter);

但是这不起作用。有什么错误吗?

TypeError: Converting circular structure to JSON
--> starting at object with constructor 'NativeTopology'
| property 's' -> object with constructor 'Object'
| property 'sessionPool' -> object with constructor 'ServerSessionPool'
--- property 'topology' closes the circle
at JSON.stringify (<anonymous>)
at stringify (F:\work\find-stuff\backend\node_modules\express\lib\response.js:1123:12)
at ServerResponse.json (F:\work\find-stuff\backend\node_modules\express\lib\response.js:260:14)
at F:\work\find-stuff\backend\src\controllers\room.controller.ts:75:27
at Generator.next (<anonymous>)
at F:\work\find-stuff\backend\src\controllers\room.controller.ts:8:71
at new Promise (<anonymous>)
at __awaiter (F:\work\find-stuff\backend\src\controllers\room.controller.ts:4:12)
at createItem (F:\work\find-stuff\backend\src\controllers\room.controller.ts:59:16)
at Layer.handle [as handle_request]

我对此感到非常困惑。

最佳答案

Model.find是一个异步操作,需要使用 .then() 或传递回调来等待/继续:

const items = await Room.find(filter);

关于node.js - 如何编写给定 mongodb 查询的 mongoose 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60405551/

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