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

Select few fields as array in mongoose express

本文关键字:几个 字段 数组 express mongoose 选择      更新时间:2023-09-26

如果在我的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;
} 

注意:不要更改模式。。。只有在服务中,才能将数据字段分离到两个数组中,并获取数据。。。。。
帮助提前感谢

我假设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;
        });
}