我有這個模型:
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陣列串列中獲取,但當我嘗試使用 搜索它時,它會由于某種原因include回傳,無論我將其搜索為 a還是作為.falseStringObjectId
知道發生了什么嗎?
uj5u.com熱心網友回復:
Array.prototype.includes 將每個元素與樣本進行比較,直到找到匹配項。只有當物件參考同一個類的實體時,它們才被認為是相等的。當您呼叫建構式const element_to_search = ObjectId("60dcbb29118ea36a4f3ce229"); 時,它會創建一個從未出現在陣列中的新實體,即使它的值相同。
您需要比較標量。字串例如:
friends_ids.map(f => f.toString()).includes("60dcbb29118ea36a4f3ce229");
或在您首先構建時將其轉換為字串,friends_ids以避免在陣列上產生額外的回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/497670.html
標籤:javascript mongodb 猫鼬 nosql 梅尔
