简体   繁体   中英

Express.js, Mongoose: Populate returns null

I'm learning express.js and mongoDB and want to create a functionality, where user should be able add products. My code contains 2 models, User and Product . User has a reference to Product . In User query when i try to populate Product ', null is returned.
I'm testing it with postman , and the result is null in cart .
I am a beginner and don't understand how to solve the issue.


user schema

import mongoose, { Document } from 'mongoose'

export type ProductDocument = Document & {
  name: string;
  description: string;
  categories: string[];
  variants: string[];
  sizes: number[];
}

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    index: true,
  },
  description: {
    type: String,
  },
  categories: [String],
  variants: [String],
  sizes: [Number],
})

export default mongoose.model<ProductDocument>('Products', productSchema)



product schema

export const getProduct = async (req: Request, res: Response) => {
    try {
        const { productId } = await req.body
        const productBought = await Products.findOne({ _id: productId }).then(
            (product) => {
                return product
            }
        )
        console.log(productBought)

        const updated = await Users.findOneAndUpdate(
            { _id: req.params.userId },
            { $push: { cart: productBought } },
            { new: true }
        )
            .populate('cart')
            .exec()
        return res.json(updated)
    } catch (error) {
        return res.status(404).json({ message: 'does not work' })
    }
}

and the controller for responsible for populating


{
    "isAdmin": false,
    "cart": [
        null,
        null
    ],
    "_id": "5f894b3c06b4a108f8d9a7ab",
    "firstName": "John",
    "lastName": "Doe",
    "password": "$2b$08$rA0/r8iVBWeSyyerPDpPWO.ztgouQoseX0QFBZ.mlPgb6tELlrhpy",
    "email": "john@gmail.com",
    "__v": 0
}

output from postman

{ "isAdmin": false, "cart": [ null, null ], "_id": "5f894b3c06b4a108f8d9a7ab", "firstName": "John", "lastName": "Doe", "password": "$2b$08$rA0/r8iVBWeSyyerPDpPWO.ztgouQoseX0QFBZ.mlPgb6tELlrhpy", "email": "john@gmail.com", "__v": 0 }

your "cart" like[ObjectId,ObjectId], but your "productBought" like[{},{}].

try let cart = [];productBought.forEach((v,k) => {cart[k] = v._id});

and use { $push: { cart: { $each: cart } },

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