skip to Main Content

My collection looks like this: (Don’t ask me why it’s an array inside of a collection)

const postsSchema = mongoose.Schema({
    posts: {type: Array},
})

I want to find a document in it and I tried this:

Posts.aggregate([
        {
            $match:{
                'posts': { _id: new ObjectId(req.query.postId), }
            }
        }
])

And this:

Posts.find({
   posts: {
        $elemMatch: { "_id" : new ObjectId(req.query.postId) }
   }
})

And this:

Posts.findOne({
     'posts._id': new ObjectId(req.query.postId)
})

2

Answers


  1. const { postId } = req.query.postId;
    const result = await Posts.findOne({ _id: postId })
    

    If you use async function you can put await else you can do .then method to get the result and avoid the await keyword

    Login or Signup to reply.
  2. to help you I can show you this code I made in typescript.

    use the await to retrieve the give and put your function in async

    the model (user job is the array

    const UserSchema = new Schema<UserInterface>({
        discordId: {required: true, type: "string"},
        username: {required: true, type: "string"},
        githubName: {required: true, type: "string"},
        userJob: [String],
        paypal: {type: "string", default: null},
        commandCount: {type: "number", default: 0},
        commandInProgress: {type: "number", default: 0},
    })
    

    the get and update

    let job = "BigLol"
    let result = await userModel.findOne({discordId: "0000022"});
    result.userJob.push(job)
    result.save();
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search