在mongoose express中选择几个字段作为数组

时间:2016-03-28 06:10:21

标签: javascript arrays node.js mongoose

如果在我的modle Schema数据集中,我有......

var visitSchema = new mongoose.Schema({

    title                           : { type: String},
    client                          : { type: String},
    agenda                          : { type: String},
    agm                             : { type: String },
    anchor                          :{ type: String }
  )}

所以在这里,我想要一些其他服务,将标题,客户端,议程分成一个数组和agm,锚定到其他数组中以进行检索...
所以我试过这种方式...

function getExecsById(id){
    var deferred = Q.defer();
    console.log("im in getExecsById")
    var one = ('agm anchor');
    //var two =('title client agend');
    model
    .find({ _id: id })
    .select(one)
    .exec(function (err, item) {
        item = item.map(function(doc) { return doc.one; });
        if(err) {
            console.log(err);
            deferred.reject(err);
        }
        else

            deferred.resolve(item);
    });
    return deferred.promise;

} 

注意:不要更改架构...只在服务单独的数据字段中分成两个数组并获取数据.....
请事先帮助谢谢

1 个答案:

答案 0 :(得分:2)

我假设Lodash可用。

function getExecsById(id){
    var partition = ['agm', 'anchor'];

    return model.findOne({ _id: id })
        .then(function(item) {
            var p1 = [],
                p2 = [];

            return _.each(item, function(v, k) { 
                if (partition.indexOf(k) !== -1) {
                    p1.push(v);
                } 
                else {
                    p2.push(v);
                }
            });
        })
        .catch(function(error) {
            return error;
        });
}