我正在努力讓以下代碼作業,使用 MongoDB、Mongoose 和 NodeJS。我有兩種模式,一種用于保存唯一的用戶組態檔,另一種用于保存他們的條目(這樣他們可以多次輸入)。條目都有效(此處未顯示),只是獲勝者的選擇無效。它應該從集合中隨機選擇一個條目,找到它們的唯一組態檔并將“won”布林值設定為 true 并洗掉集合中的所有條目。它目前沒有做任何這些事情(但我已經檢查了路由一切正常并且觸發了 const ),因此將不勝感激。我嘗試了各種方法,但在任何地方都沒有找到明確的指導。謝謝。
控制器
const { Enter } = require('../models/user_entry');
const { UserProfile } = require("../models/User_Profile");
const drawWinner = async (req, res) => {
const winner = Enter.aggregate([{ $sample: { size: 1 } }]);
const users_profile = await UserProfile.findOne({ handle: winner.user });
users_profile,{"$set":{"won":true}};
await users_profile.save();
Enter.deleteMany({ });
};
module.exports = {
drawWinner
};
型號:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Entry Schema
const EntrySchema = new Schema({
user: {
type: String,
required: true,
},
});
const Enter = mongoose.model("entries", EntrySchema);
module.exports = { Enter };
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Profile Schema
const UserProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
handle: {
type: String,
required: true,
trim: true,
unique: true,
},
won: {
type: Boolean,
default: false,
},
});
const UserProfile = mongoose.model("profile", UserProfileSchema);
module.exports = { UserProfile };
uj5u.com熱心網友回復:
您await在聚合資料庫時丟失了
const winner = await Enter.aggregate([{ $sample: { size: 1 } }]);
您可能還想console.log(winner)檢查是否從資料庫中獲取任何資料。
編輯
根據您的評論,您正在獲得winner.user價值
你使用更新用戶的方式很奇怪,試試這個
let updated_user = await UserProfile.findOneAndUpdate({ handle: winner.user }, { won: true },{ new: true });
您可以洗掉這 3 行
const users_profile = await UserProfile.findOne({ handle: winner.user });
users_profile,{"$set":{"won":true}};
await users_profile.save();
此外,雖然deleting條目使用await Enter.deleteMany({});
您還需要發回一些回應,res.send()否則服務器將掛起。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429518.html
