0

I am attempting to insert items at a specific index in an array that may or may not be empty. For example, say I have the following document in my mongoDb collection:

{
   title: "abe",
   questions: []
}

I would like to do something like set the 5th element in the array to a specific value. I was playing with the mongo db command line and I was able to do the following:

> mytest = []
[ ]
> mytest[4] = 'test'
test
> mytest
[ undefined, undefined, undefined, undefined, "test" ]

Which is basically what I want, but when I attempt to do this from my node.js code I am getting weird results (weird as in, items are not in the correct index). Code below:

Mongoose Schema Definition:

mongoose = require("mongoose")
Schema = mongoose.Schema

surveySchema = new Schema
    title: String
    questions: [
        type: Schema.Types.ObjectId
        ref: 'Question' 
    ]

Code doing the update:

surveys.update  {id: doc.survey_id}, 
{
    $push: { 
        questions: {
            $each: [doc._id],
            $position: doc.sort_order
        }
    }
}, 
{upsert:false, multi:true}, 
callback

The code above is being executed in an asynchronous loop, so it's possible the last item will be inserted before the first item and so on.

Can anyone see any reason why items would not be getting inserted at the correct index? Why does my basic example work but the code does not? Could it have to do with the fact that my schema defines questions as an array of ObjectIds?

3
  • In your first example, the correct serialisation of test is [,,,,'test']. The first four members of the array do not exist (i.e. they are "not defined" rather than undefined). Commented Sep 10, 2014 at 0:04
  • Sorry, what do you mean? I copied and pasted that directly from the MongoDb command line. Are they outputting it incorrectly or something? Commented Sep 10, 2014 at 0:06
  • 1
    Yes. It gives the impression that the first four members exist and have a value of undefined when they don't. Using elisions makes that clear. Commented Sep 10, 2014 at 0:22

1 Answer 1

1

Documentation for MongoDB $position: If the number is greater or equal to the length of the array, the $position modifier has no effect and the operator adds elements to the end of the array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.