[英]Mongoose remove from collection without model
My MongoDB has a sessions
collection that is created by a module. 我的MongoDB有一个由模块创建的
sessions
集合。 The collection has no model or anything since it is not created by Mongoose. 该集合没有模型或任何东西,因为它不是由Mongoose创建的。
How can I access this collection without specifying it's model? 如何在不指定模型的情况下访问此集合?
I tried the following: 我尝试了以下方法:
mongoose.connection.db.sessions.remove({'session.userId': userId}, function(e, found) {
console.log(found);
res.json({success: true});
});
Although I received the error of: Cannot read property 'remove' of undefined
虽然我收到以下错误:
Cannot read property 'remove' of undefined
Querying the collection directly will only solve part of your problem. 直接查询集合只能解决部分问题。
From the looks of it, you're using express-session
and connect-mongo
to manage sessions. 从外观上看,您正在使用
express-session
和connect-mongo
来管理会话。 This will store the session data ( req.session
) as a JSON string in the database: 这会将会话数据(
req.session
)作为JSON 字符串存储在数据库中:
{
"_id": "fLBj_McMFM-7PwVNsv9ov88vOAgoNiDa",
"session": "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"userId\":\"my-user-id\"}",
"expires": ISODate("2016-07-09T08:47:38.156Z")
}
As you can see, session
is a string, not an object, so you can't query it directly using session.userId
. 如您所见,
session
是一个字符串,而不是一个对象,因此您不能使用session.userId
直接查询它。
If you can't use req.session.destroy()
, you need to perform a regular expression query to match against the user id in the JSON string: 如果无法使用
req.session.destroy()
,则需要执行正则表达式查询以与JSON字符串中的用户ID匹配:
let collection = mongoose.connection.db.collection('sessions');
let query = new RegExp(`"userId":"${userId}"`);
collection.remove({ session : query }, function(e, found) {
console.log(found);
res.json({success: true});
});
It's probably best if userId
is first run through something like escape-string-regexp
to make sure that any special characters are escaped properly. 最好是先通过诸如
escape-string-regexp
类的代码运行userId
,以确保正确转义了任何特殊字符。
Note that this isn't a fast query, especially if you have a lot of sessions in your database. 请注意,这不是一个快速查询,尤其是在数据库中有很多会话的情况下。
EDIT : I just found the stringify
option for connect-mongo
which, if set to false
, should write the session data as a regular object to MongoDB, and not as a JSON string. 编辑 :我刚刚找到
connect-mongo
的stringify
选项,如果将其设置为false
,则应将会话数据作为常规对象写入MongoDB,而不是作为JSON字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.