Array of ObjectIds will not populate without error - javascript

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.

Related

how to return a Mongoose nested array of objects

I am trying to return a nested Object that I declared in my mongoose model as follows:
const MessageSchema = new Schema({
messageLog: [
{
transcript: {
type: String
},
recipient: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
sender: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
}]
});
however I am not able to get the value for the inner object back when I try to query for it via a graphql resolver (transcript, sender, recipient are null on gql playground, but updated in db) I have set it up as follows:
query = args.messageId ? { _id: args.messageId } : { _id: new ObjectId() };
const message = await Message.findOneAndUpdate(query, {$addToSet: {messageLog: {transcript: args.messageBody, sender: args.senderId, recipient: args.recipientId}}}, {$setOnInsert: args, upsert: true, new: true, runValidators: true})
return message.messageLog;
I am able to create the new object and the nested messageLog in the db but I can only return the id for some reason as opposed to the the messageLog array of objects. Usually the issue lies in how I am resolving (resolvers) but I am going to put my typeDef here as well in case the issue lies there.
type Message {
_id: ID
transcript: [String]
recipient: [User]
sender: [User]
}
So the solution in case anyone has a similar schema setup and issue is to reference the the typeDefs with the nested levels as well. So since transcript, recipient and sender were nested a level down, the typeDef would have to be defined for the nested object and then referenced on the message type as follows:
type messageLog {
_id: ID
transcript: String
recipient: User
sender: User
}
type Message {
_id: ID
messageLog: [messageLog]
}
and to use populate for the User since it was a schema referenced by the objectId

nest mongoose document to another collection document

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

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.

Cast to Array failed when insertind data to mongodb via express.sj

I am making a webiste using MERN stack, I've managed to insert data from forms in react front end to mongodb but when I made a new form I get a cast to array failed error. I've tried casting to another array in my mongroose model and that worked just fine. the system is a mock online bank, never to be used in any production enviournment
My model:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
// Creates the needed schema
let userSchema = new Schema({
name: String,
created_at: Date,
updated_at: Date,
balance: Number,
address: String,
ssn: Number,
bankNumber: Number,
cards: [
{
type: String, // Visa eller Mastercard
cardNumber: Number,
cvc: Number,
expirationDate: Number,
pin: Number,
status: Boolean,
dailyLimit: '9900'
}
],
whitdrawal: [
{
amount: Number,
date: Date, // Skriv auto date logikk
reason: String
}
]
});
// Inserts
userSchema.pre('save', function(next) {
const currentDate = new Date();
this.updated_at = currentDate;
this.date = currentDate;
if (!this.created_at) this.created_at = currentDate;
next();
});
// Creates model for schema
const AtmUser = mongoose.model('AtmUser', userSchema);
// Export so it is available for the rest of the application
module.exports = AtmUser;
Express method for saving this data, data is sent from front end and visible in terminal error message
app.post('/api/newUser', function(req) {
const newUser = AtmUser({
name: req.body.name,
balance: req.body.balance,
address: req.body.address,
ssn: req.body.ssn,
bankNumber: req.body.bankNumber,
cards: [
{
type: req.body.type, // Visa eller Mastercard
cardNumber: req.body.cardNumber,
cvc: req.body.cvc,
expirationDate: req.body.expirationDate,
pin: req.body.pin,
}
],
});
newUser.save(function(err) {
if(err) throw err;
console.log('A new user has been made')
})
})
When trying to cast to whitdrawal arary instead of cards array everything works as expected, part of the erorr message I get in terminal
events.js:167
[0] throw er; // Unhandled 'error' event
[0] ^
[0] ValidationError: AtmUser validation failed: cards: Cast to Array failed for value "[ { type: '234234234' } ]" at path "cards"
[0] at new ValidationError (/Users/andreas/Documents/prosjekt/atm/node_modules/mongoose/lib/error/validation.js:30:11)
I've been trying to spot the error for a few hours but just cannot find it, thank you for all replies! I'd be happy to post more of the code or the entire error message if that would help
After much trial and error I found the answer, it turns out that type is a reserved word, changing it to formType og Type solved the issue in my model.
Corrected model:
app.post('/api/newUser', function(req) {
const newUser = AtmUser({
name: req.body.name,
balance: req.body.balance,
address: req.body.address,
ssn: req.body.ssn,
bankNumber: req.body.bankNumber,
cards: [
{
formType: req.body.type, // Visa eller Mastercard
cardNumber: req.body.cardNumber,
cvc: req.body.cvc,
expirationDate: req.body.expirationDate,
pin: req.body.pin,
}
],
});
newUser.save(function(err) {
if(err) throw err;
console.log('A new user has been made')
})
})

How to reference and populate nested schemas?

TL;DR
How do you reference (and thus populate) subdocuments within the same collection?
I've been trying for a while now to populate a reference to a subdocument in my Mongoose schema. I have a main schema (MainSchema) which holds arrays of locations and contacts. The locations have a reference to these contacts.
In my location array i make a reference to these contacts by the _id of the contact. See below.
import mongoose from 'mongoose';
const LocationSchema = new mongoose.Schema({
city: {type: String},
contact: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Contact' //alternative tried: refPath: 'contacts'
}
});
const Location = mongoose.model('Location', LocationSchema);
const ContactSchema = new mongoose.Schema({
firstName: {type: String},
lastName: {type: String}
});
const Contact = mongoose.model('Contact', ContactSchema );
const MainSchema = new mongoose.Schema({
name: {type: String},
locations: [LocationSchema],
contacts: [ContactSchema]
});
export.default mongoose.model('Main', 'MainSchema');
Now when i want to populate the contact of the locations I get null or just the plain _id string returned. Below is my populate code. I've tried every combination i could find, involving making the nested documents their own models and trying different ways to reference them.
MainSchema.statics = {
get(slug) {
return this.findOne({name})
.populate('locations.contact')
.exec()
.then((company) => {
if (company) {
return company;
}
const err = 'generic error message';
return Promise.reject(err);
});
}
};
I've also tried the newer approach to no avail:
populate({
path: 'locations',
populate: {
path: 'contacts',
model: 'Contact'
}
});
I must be missing something here. But what?
edited the question to show the complete query statement as requested
After searching some more i found an exact same case posted as an issue on the Mongoose github issue tracker.
According to the prime maintainer of Mongoose this form of populate is not possible:
If you're embedding subdocs, you're not going to be able to run
populate() on the array, because the subdocs are stored in the doc
itself rather than in a separate collection.
So taking your example of schema I would do the following. Please take notice that I don't say that my approach is the best way of doing this, but I had an exact similar case as you.
Mongoose model
import mongoose from 'mongoose';
const LocationSchema = new mongoose.Schema({
city: {type: String},
contact: { type: Schema.Types.ObjectId, ref: 'Contact'}
});
const ContactSchema = new mongoose.Schema({
firstName: {type: String},
lastName: {type: String}
});
const MainSchema = new mongoose.Schema({
name: {type: String},
locations: [{ type: Schema.Types.ObjectId, ref: 'Location' }],
});
const Main = mongoose.model('Main', MainSchema);
const Location = mongoose.model('Location', LocationSchema);
const Contact = mongoose.model('Contact', ContactSchema );
Note: In your main schema I've removed the contacts since I understand from your example that each location has it's own contact person, so actually in the MainSchema you don't need the ContactSchema
The controller where the you insert the data
The idea here is that you have to pass the reference _id from each document to the other one, the below example is mock-up please adapt it to fit your app. I used a data object that I assume that has one location and one person contact
async function addData(data) {
//First you create your Main document
let main = await new Main({
name: data.name
}).save();
//Create the contact document in order to have it's _id to pass into the location document
let contact = await new Contact({
firstName: data.fistName,
lastName: data.lastName
});
//Create the location document with the reference _id from the contact document
let location = await new Location({
city: data.city,
contact: contact._id
}).save();
//Push the location document in you Main document location array
main.locations.push(location);
main.save();
//return what ever you need
return main;
}
Query
let mainObj = await Main.findOne({name})
.populate({path: 'locations', populate: {path: 'contact'}})
.exec();
This approach is working for me, hope it serves you as well

Categories