#node.js #mongoose
#node.js #мангуст
Вопрос:
У меня есть модель члена, где в члене семейства находится вложенный документ, я пытаюсь поместить массив объектов в вложенный документ! Пожалуйста, помогите мне
Модель члена
const memberSchema = new Schema({
fullName: {
type: String,
required: true,
trim: true
},
gender: {
type: String,
required: true
},
dateOfBirth: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
caste: {
type: String,
required: true
},
education: {
type: String,
required: true
},
occupation: {
type: String,
required: true
},
profession: {
type: String,
required: true
},
address: {
street: {
type: String,
required: true
},
city: {
type: String,
required: true
},
district: {
type: String,
required: true
}
},
jobAlerts: {
type: String,
enum: ['yes', 'no'],
required: true
},
jobTraining: {
type: String,
enum: ['yes', 'no'],
required: true
},
// state: {
// type: String,
// required: true,
// trim: true
// },
// taluk:{
// type: String,
// required:true,
// trim:true
// },
userId: {
type: Schema.Types.ObjectId,
ref: "User"
},
familyMembers: [{ familyMemberSchema }],
isDeleted: {
type: Boolean,
default: false
},
verificationStatus: {
type: Boolean,
default: false
},
paymentStatus: {
type: Boolean,
default: false
},
referredBy: {
type: String,
required: true
}
});
memberSchema.plugin(timeStamp);
const Member = mongoose.model("Member", memberSchema);
Схема члена семейства
const familyMemberSchema = new Schema({
familyReference: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Member'
},
fullName: {
type: String,
required: true
},
gender: {
type: String,
required: true
},
dateOfBirth: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
education: {
type: String,
required: true
},
occupation: {
type: String,
required: true
},
profession: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = {
familyMemberSchema
}
Пользовательский контроллер
router.post("/register/member", authenticateUser, authorizeVolunteer, async (req, res) => {
let body;
let volunteer = req.user.username
try {
body = req.body
// User.findOne(body.mobile).then(registeredUser =>{
// if(!registeredUser){
// }
// })
if (body.familyMembers.length !== 0) {
let user = new User()
let member = new Member()
user.username = body.username
user.mobile = body.mobile
user.password = body.password
let newUser = await user.save()
member.fullName = body.fullName
member.gender = body.gender
member.dateOfBirth = body.dateOfBirth
member.age = body.age
member.caste = body.caste
member.education = body.education
member.occupation = body.occupation
member.profession = body.profession
member.jobAlerts = body.jobAlerts
member.jobTraining = body.jobTraining
member.address.street = body.address.street
member.address.city = body.address.city
member.address.district = body.address.district
body.familyMembers.forEach((familyMember) => {
// return (
User.findOne({ mobile: familyMember.mobile }).then(registeredUser => {
if (!registeredUser) {
let user = new User()
user.username = familyMember.username
user.mobile = familyMember.mobile
user.password = familyMember.password
let newMember = {}
newMember.fullName = familyMember.fullName
newMember.gender = familyMember.gender
newMember.dateOfBirth = familyMember.dateOfBirth
newMember.age = familyMember.age
newMember.education = familyMember.education
newMember.occupation = familyMember.occupation
newMember.profession = familyMember.profession
newMember.userId = user._id
newMember.familyReference = member._id
member.familyMembers.push(newMember)
user.save()
// .then(newUser => console.log(newUser))
} else {
res.send("User already exists")
}
})
// )
})
// console.log(body.familyMembers)
console.log(member.familyMembers)
member.verificationStatus = true
member.referredBy = volunteer
let newMember = await member.save()
res.send({
notice: "Successfully Registered",
newMember
})
} else {
const { username, age, mobile, password, fullName, gender, dateOfBirth, caste, education, occupation, profession, jobAlerts, jobTraining, address: { street, city, district } } = body
User.findOne({ mobile } || { username }).then(registeredUser => {
if (!registeredUser) {
let user = new User({ username, mobile, password })
let member = new Member({ fullName, age, gender, dateOfBirth, caste, education, occupation, profession, jobAlerts, jobTraining, address: { street, city, district } })
member.userId = user._id
user.roles = 'member',
member.verificationStatus = true
member.referredBy = volunteer
Promise.all([member.save(), user.save()]).then(member => {
res.send({
notice: 'Successfully registered',
member,
status: 201
})
})
} else {
res.send("User already exists")
}
})
}
} catch (error) {
res.send({
status: 404,
error: error.message
})
}
})
Я хочу, чтобы данные о членах семейства были помещены в вложенный документ, каждый раз, когда я перебираю re.body и создаю объект и помещаю данные в БД, но этого не происходит
Ответ №1:
body.familyMembers.forEach((familyMember) => {
итерации выполняются слишком быстро, используйте асинхронность с обратным вызовом, чтобы ваш цикл сначала ожидал User.findOne
завершения выполнения.
если вы утешаете свой массив во время выполнения запроса, то это показывает, что до сих пор было повторено слишком много записей
Комментарии:
1. Пожалуйста, уточните!, Я хочу поместить это свойство body.familyMembers в вложенный документ, определенный в модели members
Ответ №2:
var asyncLoop = require('node-async-loop');
asyncLoop(array, function (directory, next) {
// your MongoDB query, your next iteration will not call untill you call next();
next(); // it will call next iteration of your array
}, function (err) {
if (err)
{
console.error('Error: ' err.message);
return;
}
console.log('Finished!'); // it show your looping is done
});