Nodejs mongoose怎么匹配对象中对象的属性?
Nodejs mongoose怎么匹配对象中对象的属性?
{
“name”: “peter”,
“time”: {
“year”: “2014”,
“month” “2014-12”
}
}
上面这个对象可以用 db.collection.find(name: “peter”) 找到,但如果想用 time.month 匹配该怎么找呢? 尝试使用 where() 结果返回
TypeError: Object DBQuery: db.collection -> { } has no method ‘where’
要使用 Mongoose 在 MongoDB 中查询嵌套对象中的属性,可以通过点符号来访问嵌套的对象。例如,如果你想根据 time.month
属性进行匹配,可以使用 Mongoose 的查询方法来实现。
以下是一个具体的示例代码,展示了如何使用 Mongoose 查询嵌套对象中的属性:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// 定义一个模式
const userSchema = new Schema({
name: String,
time: {
year: String,
month: String
}
});
// 创建模型
const User = mongoose.model('User', userSchema);
// 连接到MongoDB数据库
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });
// 示例数据插入
async function insertData() {
const newUser = new User({
name: 'peter',
time: {
year: '2014',
month: '2014-12'
}
});
await newUser.save();
}
// 查询数据
async function queryData() {
try {
// 使用点符号访问嵌套属性
const users = await User.find({ 'time.month': '2014-12' });
console.log(users);
} catch (error) {
console.error(error);
}
}
// 插入数据
insertData().then(queryData);
在这个示例中,我们首先定义了一个用户模式 userSchema
,其中包含 name
和 time
对象,time
对象又包含了 year
和 month
属性。然后我们创建了一个 User
模型,并连接到本地的 MongoDB 数据库。
接下来,我们通过 insertData
函数向数据库中插入一条示例数据。最后,在 queryData
函数中,我们使用 User.find
方法查询 time.month
等于 '2014-12'
的文档。
注意,Mongoose 不支持 where()
方法,直接使用 find
方法并使用点符号来访问嵌套属性即可实现查询功能。
好吧,知道了。
db.collection.find({time: {year: '2014'}})
db.collection.find({ “time.year” : “2014” })
要在 Mongoose 中根据嵌套对象的属性进行查询,可以使用点符号(.
)来访问嵌套字段。以下是如何根据 time.month
字段匹配文档的示例。
示例代码
假设你有一个名为 User
的 Mongoose 模型,并且你的集合中的每个文档具有类似以下的结构:
{
name: 'peter',
time: {
year: '2014',
month: '2014-12'
}
}
你可以通过以下方式查询 time.month
字段:
const User = require('./models/User'); // 引入你的 Mongoose 模型
// 使用点符号访问嵌套的 time.month 字段
User.find({ 'time.month': '2014-12' }, (err, users) => {
if (err) {
console.error(err);
} else {
console.log(users); // 这将返回所有 time.month 为 '2014-12' 的用户
}
});
解释
User.find()
是 Mongoose 提供的用于查询数据库的方法。- 在查询条件对象
{ 'time.month': '2014-12' }
中,'time.month'
使用点符号来表示time
对象中的month
字段。 - 如果查询成功,回调函数会返回匹配的文档数组。
注意
- 不需要使用
.where()
方法来查询嵌套字段。 - 确保你已经正确地定义了 Mongoose 模型,并且模型与数据库中的集合名称相匹配。
通过这种方式,你可以轻松地根据嵌套对象中的特定字段来过滤和查询数据。