我有一系列評論,我只想從模式內的一組物件中檢索評論。
這是我的架構:
const sellerSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
reviews: [
{
by: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
title: {
type: String,
},
message: {
type: String,
},
rating: Number,
imagesUri: [{ String }],
timestamp: {
type: Date,
default: Date.now,
},
},
],
});
如果 'by' 將是 req.user._id,我如何從陣列中獲得單個評論。我有以前的代碼,但它不能只檢索滿足查詢的評論。
try {
const seller_id = mongoose.Types.ObjectId(req.params._id);
const review = await Seller.findOne(
{ _id: seller_id },
{ reviews: { $elemMatch: { by: req.user._id } } } //get the review that matches to the user_id
);
res.status(200).send(review);
} catch (err) {
//sends the status code with error code message to the user
res.status(502).send({
error: "Error retreiving review.",
});
}
這將檢索整個賣方檔案,但我只想使用給定的 user_id === by: ObjectID 檢索物件評論
uj5u.com熱心網友回復:
試試看
try {
const seller_id = mongoose.Types.ObjectId(req.params._id);
const review = await Seller.findOne(
{ _id: seller_id , "reviews.by": req.user._id}, { "reviews.$": 1 }
);
res.status(200).send(review);
}
uj5u.com熱心網友回復:
嘗試將用戶也轉換_id為ObjectId并將您的條件統一到一個物件中:
try {
const seller_id = mongoose.Types.ObjectId(req.params._id);
const user_id = mongoose.Types.ObjectId(req.user._id);
const review = await Seller.findOne({
_id: seller_id,
reviews: { $elemMatch: { by: user_id } },
});
res.status(200).send(review);
} catch (err) {
//sends the status code with error code message to the user
res.status(502).send({
error: 'Error retreiving review.',
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473944.html
標籤:javascript 节点.js mongodb 表示 猫鼬
