0

I am running node.js server (with express & jade) and mongodb database. I have a function where I query mongodb using findOne. The document is about a user along with an array element that has their preferences. So the schema looks like this...

var userSchema = mongoose.Schema({

  username        : { type: String, index: true },
  preferences   : [{
              _id : mongoose.Schema.ObjectId,
              title : String,
              color : String,
              shape : String,
              }]
});


UserTabs.findOne({ 'username' :  userID }, function(err, data) {

//How do I manipulate data.preferences to change array order....
}

I pass data.preferences object to jade and print the array content list.

Question: Within the findOne function how can I manipulate the data.preferences object so I can re-arrange the array element's order and then pass the new object back to jade? BTW: what object type is this data?

FYI - I do not want to change the order in the database.

1 Answer 1

1

If you want to manipulate the results of a Mongoose query, it's usually best to call lean() on the query so that you directly get a plain JavaScript object that you can freely modify. Otherwise it's a Mongoose model instance that's not as easy to manipulate:

UserTabs.findOne({ 'username' :  userID }).lean().exec(function(err, data) {
    // data is a JavaScript object, modify it as needed.  Use the standard
    // JavaScript array manipulation functions to modify data.preferences.
    ...
}
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.