mongoose schema:
const userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
industry: {
type: String,
required: true
},
members: [
{
name: {
type: String,
required: true
},
contact: {
email: {
type: String,
required: true
},
phone: {
type: String
}
},
role: {
type: String,
required: true
}
}
]
});
需要使用查询的电子邮件检索成员。 mongo shell命令:
db.users.find({"members.contact.email": "johndoe@acmecorp.com"}, {"members.$": 1});
完美地获取结果:
{
"_id" : ObjectId("5b17cde35b5da82e2e8bb013"),
"members" : [
{
"name" : "John Doe"
"contact" : {
"email" : "johndoe@acmecorp.com"
},
"_id" : ObjectId("5b18d38c869d6c409e17292f"),
"role" : "Network Engineer"
}
]
}
尝试在node.js应用中实现此查询时,用户'模型函数定义为:
// Get member by email
module.exports.getMemberByEmail = function(email, callback) {
var query = {{"members.contact.email": email}, {"members.$": 1}};
User.find(query, callback);
};
但是语法错误:
var query = {{"members.contact.email": email}, {"members.$": 1}};
^
SyntaxError: Unexpected token {
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/home/demoapp/routes/users.js:5:14)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
对MEAN堆栈有点天真。任何有关正确语法的帮助都表示赞赏。
环境: