我有一个包含子文档数组的文档:
{
"company": "test plc",
"address": [
{
"addr1": "37",
"addr2": "",
"addr3": "test",
"addr4": "",
"addrcity": "",
"addrcounty": "test",
"addrpostcode": "test"
},
{
"addr1": "37",
"addr2": "",
"addr3": "test",
"addr4": "",
"addrcity": "",
"addrcounty": "test",
"addrpostcode": "test"
},
{
"addr1": "37",
"addr2": "",
"addr3": "test",
"addr4": "",
"addrcity": "",
"addrcounty": "test",
"addrpostcode": "test"
}
],
"contacts": [
{
"name": "test",
"surname": "testing",
"title": "master"
},
{
"name": "test",
"surname": "testing",
"title": "master"
}
]
}
我想要做的是通过搜索contacts.surname
属性来返回文档列表。
var leads = Lead.find({"contact.surname":req.params.name});
这会导致错误“将循环结构转换为JSON”,但我不确定原因。
在编辑时添加:
这是我的收藏架构:
var leadsSchema = new Schema({
company: String,
address:
[
{
addr1: String,
addr2: String,
addr3: String,
addr4: String,
addrcity: String,
addrcounty: String,
addrpostcode: String
}
],
contacts:
[
{
name: String,
surname: String,
title: String
}
]
});
var Lead = mongoose.model('leads', leadsSchema);
这是我的两个路由器:
这将从集合find中返回所有内容:
router.get('/', function(req, res) {
Lead.find({}).exec(function(err, leads) {
res.send(leads);
});
});
这会导致循环错误:
router.get('/findByContactName/:surname', function(req, res) {
var leads = Lead.find({"contacts.surname":req.params.name});
res.send(leads);
});
答案 0 :(得分:4)
试试这个
router.get('/findByContactName/:surname', function(req, res){
Lead.find({"contacts.surname":req.params.name}).exec(function(err, leads){
res.send(leads);
});
答案 1 :(得分:0)
或者尝试这个
router.get('/findByContactName/:surname', async function(req, res) {
const leads = await Lead.find({"contacts.surname":req.params.name});
res.send(leads);
});
答案 2 :(得分:0)
TL; DR:
更改var leads = Lead.find({"contacts.surname":req.params.name});
收件人:
var leads = await Lead.find({"contacts.surname":req.params.name});
说明
model.find()仅返回查询。它不会为您执行查询。因此,“ leads”变量当前是Mongoose查询文档。
当您进行res.send(leads)时,请在内部进行表达:
JSON.stringify(leads)
stringify()无法将圆形结构转换为JSON。因此,错误。
如果这里有人可以阐明为什么Mongoose查询文档是圆形结构,那就太好了!