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".
Related
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]
});
const Schema = mongoose.Schema;
const userSchema = Schema({
helper_member: { type: Schema.Types.ObjectId, ref: 'onModel'},
sponser_member: { type: Schema.Types.ObjectId, ref:'onModel'},
onModel: {
type: String,
required:true,
enum: ['user','admin']
},
});
const User = mongoose.model('user', userSchema);
module.exports = {User} ;
find().populate('sponser_member helper_member',{ _id:0,full_name: 1,user_name:1,designation:1,earnings:1})
I have tried this but no use
so how can I do this if I have multiple fields
Im not very sure what the problem is but try this:
const result = await User.find({}).populate("helper_member sponser_member")
This should find all users in the database and populte the fields by reference.
Also make sure that the reference does actually exists.
I'm new and trying to set up my noSQL DB model and am struggling. The intention is that "venues" can create events (tied to the venue), and "artists" can match-to and subsequently plan events. If you're an artist, you could also look at your dashboard and see the events you've played, so I need to connect Artists to Venues/events but don't know how.
Below is my Venue model. It works fine in my app, but where do I add Artists in?
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const VenueSchema = new Schema({
title: String,
image: String,
price: Number,
description: String,
location: String
});
module.exports = mongoose.model('Venue', VenueSchema);
Below is my Artist model. I haven't tested this one but I think it will work okay.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const artistSchema = newSchema({
name: {
type: String,
required: [true, 'Artist must have a name']
},
genre: {
type: String
},
email: {
type: String,
required: [true, 'Contact email required']
},
})
Other than Artist and Venue, I'd like "events" to contain attributes "time" and "date". However, I have no idea where to fit events into the model.. How do I connect "events" between the two models?
I would design it like this
Venue schema (Same as yours): Where all the venues can be maintained independently of events and artists.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const VenueSchema = new Schema({
title: String,
image: String,
price: Number,
description: String,
location: String
});
module.exports = mongoose.model('Venue', VenueSchema);
Artist schema (same as yours): Where all the artists can be maintained independently of events and venues.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const artistSchema = newSchema({
name: {
type: String,
required: [true, 'Artist must have a name']
},
genre: {
type: String
},
email: {
type: String,
required: [true, 'Contact email required']
},
})
module.exports = mongoose.model('Artist', artistSchema);
Events schema: This is where artists and venue come together. Since there will be continuous operations on events (like updating progress) it can be done independently of artists and venues.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventSchema = new Schema({
venue_id: {
type: Schema.Types.ObjectId,
ref: 'Venue',
index: true
},
artist_id: {
type: Schema.Types.ObjectId,
ref: 'Artist',
index: true
},
created: {
type: Date, // Captures both date and time
default: Date.now
}
});
module.exports = mongoose.model('Event', eventSchema);
i have 2 Schema like bellow, i need to get 50 item from videoInfos which not have in userInfos.watched (this array content _id of videoInfos). Please use syntax like videoInfos.find().exce if you can.
const userSchema = new mongoose.Schema({
username:String,
password:String,
point: Number,
watched: Array,//content _id of videoInfos
running: Array,
});
const userInfos = mongoose.model('userInfos', userSchema);
//======================================================
const videoSchema = new mongoose.Schema({
owner:String,
videoID:String,
totalTime: Number,
totalView:Number,
finish: Number,
didFinish:Boolean,
});
const videoInfos = mongoose.model('videoInfos', videoSchema);
Since you are using mongoose you can achieve it like this.
Change the schema like this:
const userSchema = new mongoose.Schema({
username:String,
password:String,
point: Number,
watched: [{ type: Schema.Types.ObjectId, ref: 'videoInfos' }],
running: Array,
});
And query like this:
userInfos.find({}).populate('watched');
The watched array should be populated with videoInfo data.
For more, take a look at mongoose populate.
As a beginner in node js I cannot wrap my head around following problem.
import { createSchema, Type, typedModel } from "ts-mongoose";
const CompanySchema = createSchema(
{
companyName: Type.string({ required: true, unique: true })
},
{
timestamps: true
}
);
const Company = typedModel("Company", CompanySchema);
export { CompanySchema, Company };
This all works just fine until one point. When attempting to import this file.
import {CompanySchema, Company} from "./Company";
It executes typeModel method and stores the schema as expected. However, any other import of this file Company.ts reruns this method typeModel again. Which then fails because I can register schema with the name only once. How could I prevent of reruning this and still keep access to this object?
What would be general approach to this in order to keep access to both CompanySchema and Company object(as they will be later used in another schema as a reference)?
I don't know what the createSchema and typedModel are( if they are functions created by you or part of mongoose, the versions of mongoose ive worked with didnt have these functions )
...but I think you should not "createSchema" but define it instead.
e.g
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// define schema
const messageSchema = Schema({
sender: { type: Schema.Types.ObjectId, ref: 'User' },
recipient: { type: Schema.Types.ObjectId, ref: 'User' },
createdAt: { type: Date, default: Date.now },
deletedAt: { type: Date, default: undefined },
readAt: { type: Date, default: undefined},
message: { type: String, maxlength: 5000 }
});
// create a model based on that schema
const Message = mongoose.model('Message', messageSchema);
// Export the message model ... not the schema
module.exports.Message = Message;