How to export a subdocument without creating an empty collection - javascript

I am trying to create a document that has an array of another sub-document. I need to be able to export the sub-document for use elsewhere. I am using mongoose.model and this works, however, it creates an empty collection in my database that is just never used. How can I prevent this behavior?
Usage example:
const mongoose = require("mongoose");
const ChildSchema = new mongoose.Schema({
childName: String
});
const ParentSchema = new mongoose.Schema({
parentName: String,
children: [ChildSchema]
});
module.exports = {
Parent: mongoose.model("parent", ParentSchema),
Child: mongoose.model("child", ChildSchema)
}

You can do it with autoCreate and autoIndex options on your Schema:
const ChildSchema = new mongoose.Schema({
autoCreate: false,
autoIndex: false,
childName: String
});
const ParentSchema = new mongoose.Schema({
parentName: String,
children: [ChildSchema]
});

Related

Mongoose Populate, Do I have to keep schemas in the same file?

I am trying to populate by using Mongoose. This is what it looks like so far:
schema.ts
const UserSchema = new mongoose.Schema({
id: String,
name: String,
});
const UserModel = mongoose.model("User", UserSchema, "users");
const ShiftSchema = new mongoose.Schema({
userId: {
type: String,
required: true,
},
date: {
type: String,
required: true,
},
startTime: String,
endTime: String,
});
ShiftSchema.virtual("user", {
ref: "User",
localField: "userId",
foreignField: "id",
justOne: true,
});
const ShiftModel = mongoose.model("Shift", ShiftSchema, "shifts");
export default ShiftModel;
shift.ts
const shifts = await ShiftModel.find({}).populate("user");
So this code is working fine, it is working as expects and populating user data into shift data.
What I'm currently having trouble with is organizing this. I need to separate schemas into separate files however if I try to separate the userSchema and UserModel into a different file, populate doesn't work anymore. Any ideas on a workaround for this?
Also, by the way, I am using a custom ID and not the default ID supplied by MongoDB.
What I've tried:
import mongoose from "mongoose";
export const UserSchema = new mongoose.Schema({
id: String,
name: String,
});
export const UserModel = mongoose.model("User", UserSchema, "users");
When I try to run my script, I get an error saying that Schema hasn't been registered for model "User".

Can I embed an object array inside a schema in Mongoose?

How would I insert an object array into a schema?My current code:
const commentSchema = new mongoose.Schema({
user: String,
content: String
})
const Comment = mongoose.model("Comment", postSchema);
const postSchema = new mongoose.Schema({
title: String,
content: String,
comments: [Comment]
});
I'm getting the error:
Invalid schema configuration: `model` is not a valid type within the array `comments`.
How should I properly insert a list of objects? I am trying to make a list of comments under each post. Thank you.
This should work
const commentSchema = new mongoose.Schema({
user: String,
content: String
})
const postSchema = new mongoose.Schema({
title: String,
content: String,
comments: [commentSchema]
});
Here is a link for mongoose Subdocuments

How to nest schemas in mongoose?

I'm trying to nest schemas using mongoose, but i got stuck and i don't really know why. Here is what i got.
My parent schema
const Comment = require("./Comment");
const BookSchema = new Schema({
_id: Number,
comments: [{ comment: Comment }],
ratings: [{ rate: Number }],
calculatedRating: Number
});
module.exports = Book = mongoose.model("book", BookSchema);
and child schema
const CommentSchema = new Schema(
{
userName: String,
rating: Number,
body: String,
submit_date: {
type: Date,
default: Date.now
}
},
{ _id: false }
);
module.exports = Comment = mongoose.model("comment", CommentSchema);
And with this setup im getting an error :
"TypeError: Invalid schema configuration: Model is not a valid type
at path comment."
I'm considering that i did something wrong with those exports but I'm not sure.
Your ./Comment should be:
const CommentSchema = new Schema(
{
userName: String,
rating: Number,
body: String,
submit_date: {
type: Date,
default: Date.now
}
},
{ _id: false }
);
module.exports = CommentSchema;
If you define as a new model as you did then it will create it's own collection and will be a new model instead of a sub document schema.

How do you set a schema property to be of type SubDocument in Mongoose?

I want to do something like this:
var userSchema = new Schema({
local: localSchema,
facebook: facebookSchema,
twitter: twitterSchema,
google: googleSchema
});
But it seems that a Schema is not a valid SchemaType.
In the SubDocuments guide, they only give an example where the child schema is put inside of an array, but that isn't what I want to do.
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]
})
It looks like you're just trying to create a sub object for each of those properties. You can accomplish this one of two ways.
Embedded in the schema itself
var userSchema = new Schema({
local: {
someProperty: {type: String}
//More sub-properties...
}
//More root level properties
});
Reusable object to be used in multiple schemas
//this could be defined in a separate module and exported for reuse
var localObject = {
someProperty: {type: String}
//more properties
}
var userSchema = new Schema({
local: localObject
});
var someOtherSchema = new Schema({
test: localObject
});

MongoDB + Node.js : How to use a Schema from an external file for another Schema?

I have a classes (or models) that needs to use another class as part of its properties as shown below.
** Header for both files **
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
item.js
module.exports = function() {
var ItemSchema = new Schema({
name: String,
cost: Number
});
mongoose.model('Item', ItemSchema);
}
receipt.js
ItemModel = require('./item.js');
var Item = mongoose.model('Item');
module.exports = function() {
var LineItemSchema = new Schema({
item: Item,
amount: Number
});
var LineItem = mongoose.model('LineItem', LineItemSchema);
var ReceiptSchema = new Schema({
name: String,
items: [LineItemSchema]
});
mongoose.model('Receipt', ReceiptSchema);
}
In the LineItem class, I'm trying to set the type of the variable 'item' to the class type, Item, node.js or mongoose.js is screaming at me about it saying that there's a type error.
How can I use a Schema "type" from an external file?
I have no idea why you are wrapping all of this in an anonymous function. But to reference a schema from another schema, you can do the following:
var LineItemSchema = new Schema({
item: {
type: Schema.ObjectId,
ref: 'Item'
},
amount: Number
});
And of course you need to require the Schema object:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
In item.js have it return the schema from a self-executing function.
module.exports = (function() {
var ItemSchema = new Schema({
name: String,
cost: Number
});
mongoose.model('Item', ItemSchema);
return ItemSchema;
})();
Then in receipt.js you now can use the schema just like you used LineItemSchema.
var ItemSchema = require('./item.js');
// This should still create the model just fine.
var Item = mongoose.model('Item');
module.exports = function() {
var LineItemSchema = new Schema({
item: [ItemSchema], // This line now can use the exported schema.
amount: Number
});
var LineItem = mongoose.model('LineItem', LineItemSchema);
var ReceiptSchema = new Schema({
name: String,
items: [LineItemSchema]
});
mongoose.model('Receipt', ReceiptSchema);
}
This is all speculation and untested.
I was also facing the same issue then found that I can fix it by just exporting Schema from Item.js
Example:
Item.js
-----------
const ItemSchema = new Schema({
name: String,
cost: Number
});
module.exports = ItemSchema;
and can use this schema in other models like this
const ItemSchema = require('./item.js');
const LineItemSchema = new Schema({
item: {
type: ItemSchema,
}
});

Categories