lynxx
lynxx

Reputation: 596

Wrong population after document.save() in mongoose

I am trying to create a blog and return the populated blog in the following schemas :

const blogSchema = new mongoose.Schema({
    title: {
        type:String
    },
    author: {
        type: mongoose.Schema.Types.ObjectID,
        ref: 'UserTable',
        required: true
    }
});
module.exports = mongoose.model('BlogPostTable', blogSchema);

And

const userSchema = new mongoose.Schema({
    username:{
        type:String,
    },
    blogPosts: [
        {
            type: mongoose.Schema.Types.ObjectID,
            ref: 'BlogPostTable'
        }
    ]
});
module.exports = mongoose.model('UserTable', userSchema);

I am saving a blog like this:

blogRouter.post('/', async (request, response, next) => {

    const token = request.token;

    try {
        const foundUser = await userTable.findById(decodedToken.id); // Find User

        const newBlog = new blogTable({                              // Create document 
            title: request.body.title,
            text: request.body.text,
            likes: 0,
            author: foundUser._id
        });

        await newBlog.save();  // Save Blog 
        foundUser.blogPosts = foundUser.blogPosts.concat(newBlog); // update Users blogs 
        await foundUser.save(); 
        response.status(200).json(newBlog.populate('author').toJSON()); // WRONG OUTPUT 
    }

However, The Author is populated wrong. There is no username and the id is an array!

Where did I go wrong and how to fix it?

Upvotes: 1

Views: 109

Answers (1)

mickl
mickl

Reputation: 49945

You can add below line of code to see what happens in your code:

mongoose.set('debug', true);

First statement: await newBlog.save(); triggers an insertOne operation with a document having author set: author: ObjectId("...")

then you run await foundUser.save(); which explicitly sets an array of blogposts:

{ '$set': { blogPosts: [ ObjectId(...), ObjectId(...) ] }

That makes sense becuase you used concat in JS code. The thing is that there's no other third query because you're trying to run populate on existing in-memory object which won't work - populate requires a query instead of in-memory object.

So you have to query your database again to get author populated:

let userPosts = await blogTable
        .find({ author: foundUser._id })
        .populate('author');

console.log(userPosts);

which triggers two queries:

Mongoose: blogposttables.find({ author: ObjectId("...") }, { projection: {} })
Mongoose: usertables.find({ _id: { '$in': [ ObjectId("...") ] } }, { projection: {} })

Upvotes: 1

Related Questions