0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.