【发布时间】:2020-06-09 19:58:38
【问题描述】:
这是选择包含 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]
我对此感到非常困惑。
【问题讨论】:
-
它返回一个空数组还是别的什么?您是否等待/然后在最后一行代码中返回的承诺?
-
我认为您的搜索查询错误!.
-
谢谢,@mickl,我很傻。缺少“等待”是问题所在。请写答案文章。我会接受的。
标签: node.js mongodb mongoose nosql filtering