Create ref to sub document's array for each property of subdocument - mongodb

Model A looks like
{ a : {
step1: [{
type: { type: String },
category: { type: String },
}],
step2: [{
type: { type: String },
category: { type: String },
}]
} }
Model B which I wanted to create should contain a prop which will ref to Model A.step1 or A.step2 , trying to acheive this by following
{ progress : [
{
step: {
type: Schema.Types.ObjectId,
ref: "A.a.{What should be here}",
required: true,
},
details: { type: Schema.Types.Mixed },
}
]
}

I think you need to create Schemas for all of them :)
I would just separate the three completely - not sure if this is viable to you as the whole idea behind this is a bit mysterious, but would something like this work for you?
const stepSchema = new Schema({
type: String,
category: String,
});
const Step = mongoose.model("steps", stepSchema);
const aSchema = new Schema({
step1: [stepSchema],
step2: [stepSchema],
});
const A = mongoose.model("as", aSchema);
const progressSchema = new Schema({
a: { type: aSchema, required: true, ref: "as"},
progress: [{ type: stepSchema, required: true, ref: "steps" }],
details: Schema.Types.Mixed,
});
const Progress = mongoose.model("progresses", aSchema);

Related

how to use nested object as a ref in mongoose

I have two schemas user and note-
user schema
import mongoose from 'mongoose';
const userSchema = mongoose.Schema({
id: {
type: String,
},
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
notes: [
{
type: mongoose.Types.ObjectId,
ref: 'Note',
},
],
folders: {
type: [
{
name: {
type: String,
},
notes: [
{
type: mongoose.Types.ObjectId,
ref: 'Note',
},
],
},
],
default: [
{ name: 'My Notes', notes: [] },
{ name: 'Todos', notes: [] },
{ name: 'Projects', notes: [] },
{ name: 'Journals', notes: [] },
{ name: 'Reading list', notes: [] },
],
},
});
const User = mongoose.model('User', userSchema);
export default User;
note schema
import mongoose from 'mongoose';
const noteSchema = new mongoose.Schema({
id: {
type: String,
required: true,
},
modify_date: {
type: String,
required: true,
},
modify_time: {
type: String,
required: true,
},
tags: [
{
id: {
type: String,
required: true,
},
text: {
type: String,
required: true,
},
},
],
created_by: {
type: mongoose.Types.ObjectId,
ref: 'User',
required: true,
},
folder: {
type: String, //can I use ref from user?
},
title: {
type: String,
},
body: {
type: String,
required: true,
},
time_stamp: {
type: Date,
required: true,
},
});
const Note = mongoose.model('Note', noteSchema);
export default Note;
I have searched but could not find anything. I want to use the nested folder object from user schema as a ref in note schema; so, whenever I change or update a folders name all the notes get the updated value. Is it possible?
If not should I make a separate folder schema and add ref of folder schema in both note and user? How can I achieve that, any suggestion might be very helpful?

How to develop nested condition query in mongoDB

I am pretty new to mongoDb and want to apply nested query.
I have a business schema like this:
const businessSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
businessType: {
type: Schema.Types.ObjectId,
ref: "businessCategory",
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
select: false,
},
review: {
type: [reviewSchema],
},
isDeleted: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
Business has a review where user can do the review and reviewSchema is
const reviewSchema = new mongoose.Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: "users",
required: true,
},
rating: {
type: Number,
enum: [1, 2, 3, 4, 5],
},
reviewArray: {
type: [singleReviewSchema],
},
},
{ timestamps: true }
);
One user can do many reviews, and it has reviewArray.
ReviewArray schema is
const singleReviewSchema = new mongoose.Schema(
{
title: {
type: String,
},
description: {
type: String,
},
isDeleted: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
How to fetch the business with a condition business: isDeleted:false and its reviews with singleReviewSchema: isDeleted:false
I dont know your model names, so please replace path with correct names
but it might look like:
businnesModel.find({isDeleted: false})
.populate({
path: 'reviewModelName',
model: 'review',
populate: {
path: 'reviewArray',
model: 'singleReviewModelName',
match: {
isDeleted : false
}
}
})
It should provide you array of businessModel documents - even when their singleReviews array will be empty (because all of reviews are deleted, or there was zero reviews). So you have to filter it out in JS.
To avoid filtering in JS, and to do it a bit more efficient way for mongodb, you can go with aggregate instead.

Collection referencing multiple collections

I want to have a collection with multiple fields referencing multiple collections, something like it:
var comboSchema = new Schema({
oneId: { type: Schema.Types.ObjectId, ref: "One" },
twoId: { type: Schema.Types.ObjectId, ref: "Two" },
threeId: { type: Schema.Types.ObjectId, ref: "Three" },
components: {
id: {type: Schema.Types.ObjectId, ref: "Component"},
amount: {type: Number}
}
}
I know I can use $lookup and aggregate to get data, but it looks like it works only on a single field in a collection?
Any help? Thank you! :-)
This is a model sample using the ref, the ref key in the object will take the name of the model in which you are referencing
const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
text: {
type: String,
required: 1
},
mediatype: {
type: String,
required: 1
},
media: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
likes: {
type: [{
userid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}
}]
},
comments: {
type: [{
userid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
comment: String
}]
},
}, {
timestamps: true
})
const Post = mongoose.model('post', postSchema)
module.exports = Post
so you can then populate it like Post.find().populate('user')

Ordering two reference arrays together

Suppose I have the following schemas:
var QuizSchema = new mongoose.Schema({
name: { type: String, required: true },
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }],
questionGroups: [{ type: mongoose.Schema.Types.ObjectId, ref: 'QuestionGroup' }]
});
var QuestionSchema = new mongoose.Schema({
number: { type: String, required: true }, // e.g. 1, a, i, anything
question: { type: String, required: true },
type: { type: String, enum: ['multiple choice', 'multiple select', 'short answer'] },
choices: [String],
answers: [String]
});
var QuestionGroupSchema = new mongoose.Schema({
number: { type: String, required: true }, // e.g. 1, a, i, anything
prompt: { type: String },
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }]
});
I am trying to design a way that will allow me to order questions and question groups together.
I was thinking maybe of adding a new field order
var QuizSchema = new mongoose.Schema({
// ...
order: [
{
type: { type: String, enum: ['Question', 'QuestionGroup'] },
id: mongoose.Schema.Types.ObjectId // reference
}
]
});
such that in the database, the field would contain something such as
[
{ type: 'Question', id: ObjectId('57867a34567g67790') },
{ type: 'Question', id: ObjectId('57867a34567g67765') },
{ type: 'QuestionGroup', id: ObjectId('69864b64765y45645') },
{ type: 'Question', id: ObjectId('57867a34567g67770') },
{ type: 'QuestionGroup', id: ObjectId('69864b64767y45647') }
]
This may mean that I would need to "populate" the ordered list of questions and question groups as
quiz.populate('questions questionGroups').exec(function (err, quiz) {
// sort questions and groups by the order
quiz.order = quiz.order.map(function (o) {
if (o.type === 'QuestionGroup') {
return quiz.questionGroups.id(o.id);
}
return quiz.questions.id(o.id);
});
});
So my question: is there a better way to design this?
Virtuals can come in handy here; without persisting order field in db and doing calculations on client each time:
var QuizSchema = new mongoose.Schema({
name: { type: String, required: true },
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }],
questionGroups: [{ type: mongoose.Schema.Types.ObjectId, ref: 'QuestionGroup' }]
},
{
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
}
);
QuizSchema
.virtual('order')
.get(function() {
return this.questions.concat(this.questionGroups); //questions followed by questionGroups
});
Sort on createdAt is of course optional, but for that you need to have this field in Question and QuestionGroup:
Quiz.find({}, function (err, quiz) {
//...
})
.populate({path : 'questions', options: {sort: { 'createdAt': 1 }}})
.populate({path : 'questionGroups', options: {sort: { 'createdAt': 1 }}});

Collection schema for a quiz app in Meteor

I am creating a quiz app in Meteor.
What can a schema for a question look like? I am thinking of doing something like
const QuestionSchema = new SimpleSchema({
text: {
type: String,
},
correctAnswers: {
type: [Object],
},
'correctAnswers.$.text': {
type: String,
},
wrongAnswers: {
type: [Object],
},
'wrongAnswers.$.text': {
type: String,
},
});
but is it really smart? How can I save which answer some user chose?
As #gnerkus suggests it's simpler to have a correct boolean for each answer but each answer also needs an _id so that you reference it, for example which answers did the user select?
const AnswerSchema = new SimpleSchema({
_id: { type: String },
text: { type: String },
correct: { type: Boolean }
});
const QuestionSchema = new SimpleSchema({
text: { type: String },
answers: { type: [AnswerSchema] }
});
You'll need to define a separate schema for the answers.
var QuestionSchema = new SimpleSchema({
text: {
type: String
},
answers: [{
type: SimpleSchema.Types.ObjectId,
ref: 'AnswerSchema'
}]
});
var AnswerSchema = new SimpleSchema({
text: {
type: String
},
correct: {
type: Boolean
},
question: {
type: SimpleSchema.Types.ObjectId,
ref: 'QuestionSchema'
}
});
If you need to track the answers a user picked, you'll have to store them in the user instance:
var UserSchema = new SimpleSchema({
// Define other attributes here.
answers: [{
type: SimpleSchema.Types.ObjectId,
ref: 'AnswerSchema'
}]
});