简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM