How to search on mongoose with exclude - javascript

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.

Related

Mongoose Get only size of a array

I'm using Mongoose and a MongoDB.
I have three schemas user and genres and songs.
const userSchema = new Schema({
name: String,
age: String,
favorite_genres: {
type: Schema.Types.ObjectId,
ref: 'Genre'
}
});
const genreSchema = new Schema({
name: String,
songs: {
type: Schema.Types.ObjectId,
ref: 'Song'
}
});
const songSchema = new Schema({
title: String,
artist: String,
length: String,
year: String
});
those are simplifid schemas, but they will do for this puprose.
So when I query a user I want to populate the doc with the favorite genres. But there (due to the potential amount of data) not with the ids of all songs, but only the number of songs. How can I achieve that?
I tried virtuals but they don't work the way I wanted it.
What I'm looking for is sth like the following:
const user = await User.findById(userID).populate({path: 'favorite_genres', select: 'name', sizeof: 'songs'}).lean()
// or
const user = await User.findById(userID).populate({path: 'favorite_genres', select: ['name', 'songs.length']}).lean()
Does anyone have an idea?

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

mongoose multiple reference to single field and populate same type of two fields together

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.

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
});

Categories