0
我想我對這個問題https://github.com/Automattic/mongoose/issues/1844來了。重寫貓鼬代碼,以避免版本錯誤
我可以看到會發生怎樣的情況 - 一個請求進來,測試正在更新,同時另一個請求到來,導致另一個測試更新。
我有模式,它看起來像這樣
const User = new mongoose.Schema({
_id: { type: String, default: uuid.v1 },
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
tests: [Test],
});
const Test = new mongoose.Schema(
{
_id: { type: String, default: uuid.v1 },
responses: [Response]
},
{
timestamps: true
}
);
const Response = new mongoose.Schema({
_id: { type: String, default: uuid.v1 },
answer: {
type: String,
enum: [
"StronglyAgree",
"Agree",
"SomewhatAgree",
"Neutral",
"SomewhatDisagree",
"Disagree",
"StronglyDisagree"
]
},
question: { type: String, ref: "Question" }
});
const Question = new mongoose.Schema({
_id: { type: String, default: uuid.v1 },
description: String,
});
我有一個類,UserModel
使用貓鼬的車型。
它這樣做是
async createTest(userId) {
try {
const test = await this.testModel.create();
try {
const user = await this.model.findOne({ userId });
if (user) {
user.tests.push(test);
return await user.save();
} else {
throw new Error("Non existent UserId");
}
} catch (e) {
throw e;
}
} catch (e) {
throw e;
}
}
,這就是創造的模樣。
async create() {
if (!this._model) {
await this._getModel();
}
try {
const questions = await this.questionModel.getAllQuestions();
const test = new this.model();
questions.forEach(question => {
const response = this.responseModel.create(question.id);
test.responses.push(response);
});
await this.model.populate(test, {
path: "responses.question",
model: "Question"
});
return test;
} catch (e) {
throw e;
}
}
我不知道如何重新寫這個以避免版本問題(我寧願不跳過版本控制)。該模式對我來說也很有意義,因爲我不想對問題進行重複描述(我可能不得不在將來更改描述)。
我該怎麼做?
你一直在同一件事發布變化。你實際上被告知,構建一個類似於「在實例上」的方法,實際上並不會返回承諾或回調,這只是錯誤的。對於將項添加到數組中的常見問題,您應該改爲使用['$ push'](https://docs.mongodb.com/manual/reference/operator/update/push/),同樣在[推送對象到Mongoose中的數組模式](https://stackoverflow.com/a/23452838/2313887) –
也許我誤解了你 - 你在說什麼代碼? – praks5432