简体   繁体   中英

How to retrieve an array inside a node in mongoDB using node.js?

I have a mongoDB collection called 'users'. Inside the 'users' collection there are several users. Each user has an array called Cart and there are items inside the cart like this,

在此处输入图像描述

Now I want to retrieve all the 'Cart' details (or objects) of a user by giving the user's id (_id). I tried in this way but it throws an exception

router.get('/getCart', (req, res, next) => {

    console.log(req.body.userId)
    User.findOne({_id: req.body.userId}
    ,(err, userInfo) => {
        userInfo.Cart.find({}, (err, result) => {
            if (err) return next(err);

            let cart = {
                status: 'success',
                code: 200,
                data : result
            };

            res.json(cart);
        })
    })
});

The exception

TypeError: #<Object> is not a function
    at CoreMongooseArray.find (<anonymous>)
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/src/routes/cart.js:58:23
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/node_modules/mongoose/lib/model.js:4837:16
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/node_modules/mongoose/lib/query.js:4391:12
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/node_modules/mongoose/lib/query.js:2869:28
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on Function instance at:
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/node_modules/mongoose/lib/model.js:4839:13
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/node_modules/mongoose/lib/query.js:4391:12
    at /Users/applefactory/WebstormProjects/OnlineFashionStore/src/UserBackend/node_modules/mongoose/lib/query.js:2869:28
    at processTicksAndRejections (internal/process/task_queues.js:79:11)

How can I solve this issue? Or is there any other way achieve this? Thanks in advance!

   ------------------------------ UPDATE --------------------------------------

This is my User model

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        validate: {
            validator: username => User.doesNotExist({username}),
            message: "Username already exists"
        }
    },

    email: {
        type: String,
        validate: {
            validator: email => User.doesNotExist({email}),
            message: "Email already exists"
        }
    },

    password: {
        type: String,
        required: true
    },

    Cart : {
        type: Array,
        default: []
    },

    WishList : {
        type : Array,
        default: []
    },
},{timestamps: true});

    UserSchema.pre('save', function () {
        if(this.isModified('password')){
            this.password = hashSync(this.password, 10);
        }
    });

    UserSchema.statics.doesNotExist = async function (field) {
        return await this.where(field).countDocuments() === 0;
    };

    UserSchema.methods.comparePasswords = function (password) {
        return compareSync(password, this.password);
    };

    const User = mongoose.model("User", UserSchema);
    export default User;

I think you're getting a little confused between your user model and Cart model, an approach would consist of using the user ID and querying the Cart model:

Cart.findOne({ user: user._id })

If I'm wrong, I'd highly encourage you to use references instead of a single document:

export const cartSchema = new Schema({
  user: {
    type: SchemaTypes.ObjectId,
    ref: 'User'
  }
  // ...
})

Then you can use populate:

Cart.findOne({ user: user._id }).populate('user').execPopulate()

In reality, when persisted your object will look more like:

{
  _id: '123218932183',
  cart: ['1', '2', '3'],
  wishList: ['1', '2', '3'],
  username: '...',
  // ....
}

Replacing the integer IDs with ObjectIds of course.

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