Id is created for every nested objects in documents of a collection in mongodb via mongoose - mongodb

I have a user schema. While saving document, for every nested object (quizHistory,record & responses) in document, mongoose add _id field automatically. For ref- quizHistory path
const userSchema = new Schema({
firstName: { type: String, required: true ,trim:true},
lastName:{ type: String, required: true ,trim:true},
email: { type: String, unique: true, required: true },
isUser: { type: Boolean, default: true },
password: String,
quizHistory: [{
quizId: { type: Schema.Types.ObjectId, ref: 'Quiz' },
record: [{
recordId:{ type: Number},
startTime: { type: Date },
responses: [{
quesId: { type: Schema.Types.ObjectId, ref: 'Question' },
answers: [Number]
}],
score: Number
}],
avgScore: Number
}]
})

Mongoose create virtual id by default(guide id).
Add this line to your schema.
_id : {id:false}

Related

Mongoose - Sub Document Array Issue

I have a "Company" Model which has a number of "Rooms".
I'm able to create the Rooms no problem, and they have a link back to the Company.
The problem is that when I get the Company, the Rooms array has no items.
I can see that the Room exists and has a link back to the Company:
{
"RoomType": 0,
"AllowedRoomRoles": [
"5f999f4f542eed1b8fce5fa9"
],
"Enabled": true,
"_id": "5fb677b453658c7070bf9433",
"RoomName": "Martins Room 2",
"RoomPin": "0001",
"Company": "5fad553db19ca100161a0d8f",
"__v": 0
}
However when I do:
var company = await CompanyModel.findById('5fad553db19ca100161a0d8f');
I get the Company back but the Rooms array has no items in it.
Here are my models:
//Room Schema:
const roomSchema = new Schema({
RoomPin: String,
RoomName: String,
RoomType: { type: RoomType, default: RoomType.MeetingRoom } ,
Company: {type: Schema.Types.ObjectId, ref: 'CompanySchema'},
AllowedRoomRoles: [{type: Schema.Types.ObjectId, ref: 'RoomRoleSchema'}],
Enabled: { type: Boolean, default: true },
}, {
collection: "room"
})
//Company Schema:
const companySchema = new Schema({
CompanyName: { type: String, required: true },
CompanyLogo: { type: String, required: true },
Enabled: { type: Boolean, default: true },
CompanyIdentifier: { type: String, required: true },
CompanyWebsite: { type: String, required: true },
Rooms: [{type: Schema.Types.ObjectId, ref: 'RoomSchema'}],
}, {
collection: "company"
})
Minor update:
Seems doing it this way around is fine?
```var rooms = await RoomModel.find({'Company': company._id.toString() });

Is it possible to have two types of objects in an array of mongoose schema

I am building an e-commerce application and this is my orders schema.
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema({
buyer: {
type: mongoose.Schema.Types.ObjectId,
ref: "buyer",
required: true
},
items: [{
item: {
type: mongoose.Schema.Types.ObjectId,
ref: "item",
},
quantity: {
type: Number,
default: 1
}}
],
seller: {
type: mongoose.Schema.Types.ObjectId,
ref: "seller",
required: true
},
location: {
type: {
type: "String",
enum:['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
}
},
sendAt:{
type: Date,
default: Date.now
}
});
const orderModel = mongoose.model("orders", orderSchema);
module.exports = orderModel;
I want to have an array having item-reference-id and quantity.
But with the above schema when i enter data, each item is acting as an another sub-document and having _id. Query response image.
I have found solution:
order: [
{
_id: false,
item: {
type: mongoose.Schema.Types.ObjectId,
ref: "items",
required: true,
},
quantity: { type: Number },
},
],
_id: false will stop the subdocument from creating another id for the subdocument.

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')

Updating a document in mongoDB embedded in other collections

I am still new to the concept of non-relational databases.I am using MongoDb with atlas in a node application.My collections have a lot of embedded documents, for example this mongoose schema
const feedbackSchema = new Schema({
member: {
type: userSchema,
required: true
},
datePosted: {
type: Date,
default: Date.now()
},
feedbackText: {
type: String,
required: true
}
});
const UserSchema = new Schema(
{
type: {
type: String,
required: true
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
userData: {}
},
{ strict: false }
);
member (type userSchema) is another collection.So my question is if a member in the member collection is updated,do I have to manually update this member in the feedback collection?

MongoDB: How to find the relationships between collections in database

I have a collection of user which has id, firstName, lastName. id field of user collection has been used in another collection.
Is there any way to find all collection which used user id?
user schema:
let userSchema = new mongoose.Schema({
firstName: {
type: String,
trim: true,
required: true
},
lastName: {
type: String,
trim: true,
required: true
}
},
{
timestamps: true,
usePushEach: true
});
training schema:
var trainingSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: {type: String, required: true},
institution: {
instituteName: {type: String, required: true},
type: {type: String, required: true},
address: {
country: String,
state: String,
city: String
}
},
startDate: Date,
endDate: Date,
achievements: String,
createdAt: Date,
updatedAt: Date,
endorsers: [{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
profilePic: {
container: {type: String,default: null},
name: { type: String, default: null }
},
currentPosition: {type: String,default: ""},
currentWorkingCompany: {type: String,default: ""}
}],
});
In above schema userId come from user collection
Note: similar to this which is available in MYSQL:
SELECT
ke.referenced_table_name 'parent table',
ke.referenced_column_name 'parent column',
ke.table_name 'child table',
ke.column_name 'child column',
ke.constraint_name
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
AND table_schema = 'your_db_name'
ORDER BY ke.referenced_table_name;
Source: here
You probably need MySQL function named join. In MongoDB it is named $lookup and it is part of aggregate function.