Moh*_*ain 5 mongodb node.js mongodb-query
我有 2 个模式,第一个是城市,第二个是 pincode。具有城市参考的 Pincode。他们都是这样的
城市模式
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a all city list
var allCitySchema = new Schema({
cities: {
type: String
}
}, {collection: 'allcities'});
var allcities = mongoose.model('allcities', allCitySchema);
module.exports = allcities;
Run Code Online (Sandbox Code Playgroud)
Pin 码模式
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var allPincode = new Schema({
city_id: {
type: Schema.ObjectId,
ref: 'allcities'
},
pincode: {
type: String
}
}, {collection: 'pincode'});
var allPincode = mongoose.model('pincode', allPincode);
module.exports = allPincode;
Run Code Online (Sandbox Code Playgroud)
现在的问题是,当我尝试根据城市 ID 获取所有 pincode 时,我会这样尝试
app.post('/api/getPincodeByCity', function(req, res) {
console.log("In pincode");
var cities_id = [];
cities_id = req.body.cities_id;
console.log(req.body); // { cities_id: '["5597aa08c0a0beb40be128d4","5597aa2bbb18fefc142b6915"]' }
console.log(cities_id);
pincodes.findById( {city_id: { $in: cities_id }}, function(err,pincodeIds){
if(err) res.send(err.message);
res.send(pincodeIds);
res.end('{"success" : "Recieved Successfully", "status" : 200}');
});
});
Run Code Online (Sandbox Code Playgroud)
但它不起作用给我这个错误
Cast to ObjectId failed for value "[object Object]" at path "_id"
Run Code Online (Sandbox Code Playgroud)
我也尝试使用find()
替代findById()
方法,但它给了我这个错误
undefined is not a function
Run Code Online (Sandbox Code Playgroud)
Bla*_*ven 12
该$in
运算符不仅仅“严格”用于查询数组,因为基本上可以使用任何奇异值运算符来完成此操作。
它实际上是一个“参数列表”,其计算结果为一个$or
条件,但语法更短:
var idList = ["559e0dbd045ac712fa1f19fa","559e0dbe045ac712fa1f19fb"];
var pincode = mongoose.model('pincode');
pincode.find({ "city_id": { "$in": idList } },function(err,docs) {
// do something here
});
Run Code Online (Sandbox Code Playgroud)
正如所提到的,这是这个的缩写形式:
pincode.find(
{
"$or": [
{ "city_id": "559e0dbd045ac712fa1f19fa" },
{ "city_id": "559e0dbe045ac712fa1f19fb" }
]
},
function(err,docs) {
// do something here
}
)
Run Code Online (Sandbox Code Playgroud)
您收到错误,因为您正在用“字符串”覆盖“数组”定义,除非以其他方式解析,否则所有“请求”对象都是如此。
错误的另一个原因是您调用了错误的方法。需要文档.findById()
的单个参数。_id
要查询其他字段,请.findOne()
在本例中使用 或 ,.find()
因为 an$in
可能会匹配多个文档。
归档时间: |
|
查看次数: |
25206 次 |
最近记录: |