nest mongoose document to another collection document - javascript

How to save .text of commentSchema as array format in the field of .comments in reviewSchema?
of course each review (post) has multiple comments.
// Connect to the db using mongoose
mongoose.connect("mongodb://localhost:27017/reviewdb")
// setting up model and schema for comment
var commentSchema = new mongoose.Schema( {
text: String,
user : String,
username: String,
date: Date
});
// setting up model and schema for reviews
var reviewSchema = new mongoose.Schema( {
text: String,
user : String,
username: String,
mydate: Date,
likes:{type: Number, "default":0, min:0},
comments:[commentSchema]
});
// setting up model for review
var Review = mongoose.model('review', reviewSchema);
// setting up model for comment
var comment = mongoose.model('comment', reviewSchema);

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 search on mongoose with exclude

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.

Annotate each object in MongoDB query

I have a Mongoose model with embedded documents:
const ticketSchema = new mongoose.Schema({
quantity: Number,
price: Number,
date: Date
});
const eventSchema = new mongoose.Schema({
name: String,
tickets: [ticketSchema]
});
const Event = mongoose.model('Event', eventSchema);
What I want is to extract all events with Event.find({}), but in each event, I want the date and price of the most recent ticket in the particular event, so I guess it's something like
Event.aggregate({ $groupBy: { $max: { tickets.date } });
Ii know this doesn't work, but I have to use some combination of find, aggregate, and $max.

Array of ObjectIds will not populate without error

I have the following mongoose schema:
var ChatSchema = new Schema({
pin: String,
users: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}],
messages: [{type: mongoose.Schema.Types.ObjectId, ref: 'Message'}], //<----
active: Boolean,
});
var MessageSchema = new Schema({
sent: Date,
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
content: String
});
var UserSchema = new Schema({
name: String,
pin: String,
id: String
});
This function is defined for the ChatSchema:
ChatSchema.methods.addMessageForUser = function(message, userid, userpin ) {
chat = this;
module.exports.User.findOne({id: userid, pin: userpin}).populate('messages').exec(function(err, user) {
message = {
user: user,
time: new Date(),
message: message,
};
chat.messages.push(message);
chat.save();
});
};
When I run it, I get the following error:
CastError: Cast to ObjectId failed for value "[object Object]" at path "messages"
If I remove populate('messages);` Then the error goes away, but I get another error because I try to use the messages array.
Here is the code for the models:
module.exports.Message = mongoose.model('Message', MessageSchema);
module.exports.User = mongoose.model('User', UserSchema);
module.exports.Chat = mongoose.model('Chat', ChatSchema);
Based on what you've got here, you're trying to populate backwards.
If each User had an array of Messages, then this populate call would work. It's a method on the mongoose Query object, in this case, and so it's looking for a property called messages on the documents in the User collection you're querying to pull ids from - since these aren't there, you get a weird error.
Based on what you've got here, it looks like it will work if you just remove the populate call.

Categories