简体   繁体   中英

mongodb findone return value - array manipulation

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.

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.
    ...
}

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