2015-05-14 69 views
0

值我有以下型號:貓鼬:從型號

var requestSchema = new Schema({ 
    description: { type: String, required: true }, 
    country: { type: String, index: true }, 
    shipping: [shipping], 
    deliveryLoc: { type: String, index: true }, 
    price: { type: Number, default: 0 }, 
}) 

我現在想用貓鼬拿到的價格和我不知道哪個命令我必須使用。

我想:

var pricy = _.first(_.where(request.price)); 

,它不工作,我得到了一個未定義甚至通過通過其他的查詢在相同的文件,我可以得到「發貨」。

獲取出貨機型而適用於以下命令:

var shipping = _.first(_.where(request.shipping, { type: shippingType })); 

我使用了錯誤的命令?

+0

'price'不是一個數組,那麼爲什麼你不直接以'request.price'的形式直接訪問它的值呢? – JohnnyHK

回答

0

您應該能夠使用的選擇方法如下:

// find a request 
var query = Request.findOne(); 

// selecting the `price` field 
query.select('price'); 

// execute the query at a later time 
query.exec(function (err, request) { 
    if (err) return handleError(err); 
    console.log('The price is $%s.', person.price) // The price is $6.92 
}); 

,或者通過回調:

var Request = mongoose.model('Request', requestSchema); 

// find each request with a country matching 'Zimbabwe', selecting the `price` field 
Request.findOne({ 'country': 'Zimbabwe' }, 'price', function (err, request) { 
    if (err) return handleError(err); 
    console.log('The price is $%s.', request.price) // The price is $6.92. 
}); 
+0

感謝您的回答。不幸的是,這些方法不適用於我現在要做的事情。我正在尋找更多的東西,如:var shipping = _.first(_。where(request.shipping,{type:shippingType})); 。這是給我的運輸類型回來,但不知何故它不能在價格上工作... – user3464679

+0

那麼你如何獲得Mongoose對象'request'呢? – chridam

0

首先,您需要創建您的架構類似的:

var items = new Schema({ 
    description: { type: String, required: true }, 
    country: { type: String, index: true }, 
    shipping: [shipping], 
    deliveryLoc: { type: String, index: true }, 
    price: { type: Number, default: 0 }, 
}); 

之後,您需要編譯新架構並將其添加到數據庫:

items = mongoose.model("Items", items); // The table name will be "Items" 

在創建模型,您可以執行查詢(找到或findOne):

items.findOne({price: request.price}, function (error, item) { 
    if (error) { 
    console.log(error); 
    } else { 
    console.log(item); 
    } 
}); 

的完整代碼:

var mongoose, Schema; 

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

var items = new Schema({ 
    description: { type: String, required: true }, 
    country: { type: String, index: true }, 
    shipping: [shipping], 
    deliveryLoc: { type: String, index: true }, 
    price: { type: Number, default: 0 }, 
}); 

items = mongoose.model("Items", items); 

items.findOne({price: request.price}, function (error, item) { 
    if (error) { 
     console.log(error); 
    } else { 
     console.log(item); 
    } 
});