我正在使用 Node.js 創建一個專案,其中有兩個模型:User和Project。
這是專案模型的架構:
const ProjectSchema = new mongoose.Schema({
name: {
type: String,
maxlength: 50,
required: true,
},
description: {
type: String,
maxlength: 800,
required: true
},
contributors: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}],
});
現在,對于一個專案,我想檢查當前用戶是否已經存在于專案的貢獻者中。如果用戶不存在,則添加用戶,否則,忽略。
我怎樣才能有效地檢查它?
uj5u.com熱心網友回復:
mongoose 為您提供了聚合方法,它可以完成所有作業,在您的情況下:
const projects = ProjectModel.aggregate([
{ $match: {/* query for matching a small size of projects first(you should definitely do this) */} },
{ $unwind: "$contributors" },
{ $project: { contributor: "$contributors" } }, // This stage is actually optional
{ $match: { "contributor._id": /* contributor id you want to check */ } },
{ $count: "projects" }
]);
現在您只需檢查變數并查看用戶在其貢獻者陣列中有多少專案
我測驗了這個資料集:
[{
"_id": 1,
"name": "Project1",
"contributors": [{
"_id": 11,
"name": "user1"
}, {
"_id": 22,
"name": "user2"
}]
}, {
"_id": 2,
"name": "Project2",
"contributors": [{
"_id": 22,
"name": "user3"
}, {
"_id": 44,
"name": "user4"
}]
}]
有了這個查詢:
const projects = ProjectModel.aggregate([
{ $match: { _id: 1 } },
{ $unwind: "$contributors" },
{ $project: { contributor: "$contributors" } },
{ $match: { "contributor._id": 22 } },
{ $count: "projects" }
]);
結果:
[{
"projects": 1
}]
游樂場鏈接
uj5u.com熱心網友回復:
詢問
- 找到專案
- 檢查用戶
_id是否在貢獻者陣列中 - 如果它什么都不做(保留舊值)
- 否則添加新用戶
- 替換
2為用戶id和{"_id": 2}用戶檔案
*這里沒有性能問題,我猜最多可以有 1 個專案_id,您只需進行 1 次測驗,看看它是否已經有貢獻者。
測驗代碼在這里
update(
{"_id": {"$eq": 1}}, //find the project
[{"$set":
{"contributors":
{"$cond":
[{"$in": [2, "$contributors._id"]}, "$contributors",
{"$concatArrays": ["$contributors", [{"_id": 2}]]}]}}}])
uj5u.com熱心網友回復:
更新專案檔案時需要使用$addToSet。
$addToSet 只會在沒有添加元素的情況下將元素添加到陣列中。
let user_id = req.body.user_id;
let project_id = req.body.project_id;
let data_to_update = { $addToSet:{contributors: user_id}};
Project.updateOne({ _id:project_id },data_to_update).then((updated)=>{
console.log('updated =',updated);
return res.status(200).json(updated);
}).catch((err)=>{
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/375262.html
標籤:javascript 节点.js MongoDB 表达 猫鼬
