![](/img/trans.png)
[英]Mongoose - Generate ObjectID for each object before saving document
[英]How to generate an objectId for each element when saving an array in mongoose/node?
我正在構建一個應用程序來進行簡單的調查,我正在使用 mongoose。我設置了一個實體來定義調查,這個實體包括問題和答案
const mongoose = require("mongoose");
const {User} = require("./User");
const SurveySchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: {
type: String,
minLength: 5,
maxlength: 100,
required: true
},
// other fields///
questions: [{
question: {
type: String,
minLength: 10,
maxlength: 200,
required: true
},
answers: [{
type: String,
minLength: 10,
maxlength: 100,
required: false
}],
}],
}, {timestamps: true} );
module.exports.Survey = mongoose.models.Survey || mongoose.model('Survey', SurveySchema);
當我需要向調查添加問題時,我正在這樣做(答案只是一個字符串數組)
let survey = await surveyManager.getSurvey(surveyId);
let newQuestion = {
question: question,
answers: answers
};
survey.questions.push(newQuestion);
await survey.save();
return survey;
這是我的新問題,從命令行查詢 mongodb
"questions" : [
{
"question" : "this is a question?",
"answers" : [
"answer number 1",
"answer number 2",
"answer number 3"
],
"_id" : ObjectId("63a89d2e101149d7958e0f78")
}
],
如您所見,每個問題都分配了一個 object id,這很好。 所以我的問題是,如何為每個答案分配一個 object id? 我需要它來引用然后形成另一個集合。
我想你可以像這樣聲明你的answers
,這會自動為他們分配一個_id
:
const SurveySchema = mongoose.Schema({
...
...
questions: [{
question: {
type: String,
minLength: 10,
maxlength: 200,
required: true
},
answers: [{
type: new mongoose.Schema({
answer_text: {
type: String,
minLength: 10,
maxlength: 100,
required: false
}
})
}]
}],
});
您可以將答案設置為 object,Mongoose 將為數組中的每個項目添加一個新的_id
:
questions: [{
question: {
type: String,
minLength: 10,
maxlength: 200,
required: true
},
answers: [{
answer: {
type: String,
minLength: 10,
maxlength: 100,
required: false
}
}],
}],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.