MongoDB搜索在一系列ID中,使用Include不起作用
我有这个模型:
const NeighborSchema = new Schema({
friends: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = Neighbor = mongoose.model("neighbor", NeighborSchema);
我正在尝试查看所有邻居朋友中是否存在朋友:
const mongoose = require("mongoose");
const ObjectId = mongoose.Types.ObjectId;
const testIncludes = async () => {
let neighbors = await Neighbor.find();
let friends_ids = [];
neighbors.map((neighbor) => {
const { friends } = neighbor;
friends_ids = [...friends_ids, ...friends];
});
// Returns false for this
const element_to_search = ObjectId("60dcbb29118ea36a4f3ce229");
// Returns false for this
// const element_to_search = "60dcbb29118ea36a4f3ce229";
let is_element_found = friends_ids.includes(element_to_search);
};
// Returns false in both cases
testIncludes();
即使,element_to_search
是直接从返回的friends_ids_ids
array的列表中直接拍摄的尝试使用include
搜索它,它由于某种原因返回false
,无论我是搜索为string
还是object> ObjectiD
/代码>。
知道发生了什么事吗?
I have this model:
const NeighborSchema = new Schema({
friends: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = Neighbor = mongoose.model("neighbor", NeighborSchema);
I am trying to see if a friend exists in friends of all neighbors:
const mongoose = require("mongoose");
const ObjectId = mongoose.Types.ObjectId;
const testIncludes = async () => {
let neighbors = await Neighbor.find();
let friends_ids = [];
neighbors.map((neighbor) => {
const { friends } = neighbor;
friends_ids = [...friends_ids, ...friends];
});
// Returns false for this
const element_to_search = ObjectId("60dcbb29118ea36a4f3ce229");
// Returns false for this
// const element_to_search = "60dcbb29118ea36a4f3ce229";
let is_element_found = friends_ids.includes(element_to_search);
};
// Returns false in both cases
testIncludes();
Even though, element_to_search
was taken directly from list of returned friends_ids
array, when I try to search it using include
, it returns false
for some reason, whether I search it as a String
or as an ObjectId
.
Any idea what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
array.prototype.在内,将每个元素与样品进行比较,直到找到匹配为止。仅当对象引用类的同一实例时,才被认为是相等的。当您调用构造函数
const element_to_search = ObjectID(“ 60dcbb29118ea36a4f3ce229”);
它创建了一个从未在数组中的新实例,即使其值相同。您需要比较标量。字符串例如:
或者在首先构建
friends_ids
时施放字符串,以避免在数组上进行额外的循环。Array.prototype.includes compares each element against the sample until it finds a match. Objects are considered equal only if they reference the same instance of the class. When you call a constructor
const element_to_search = ObjectId("60dcbb29118ea36a4f3ce229");
it creates a new instance which has never been in the array, even if its value is the same.You need to compare scalars. Strings for example:
or cast it strings when you build up the
friends_ids
at the first place to avoid the extra loop over the array.