Nodejs mongoose 查询问题求教
Nodejs mongoose 查询问题求教
主函数如下, 其中 mongoose 用了 bluebird 模块实现 Promise:
/** 根据查询条件生成栏目树
* {pid: 0} 全栏目树
* {_id: ObjectId('xxxx')} 指定顶级栏目栏目树
* 若 loop=false, 则只返回一层, 不递归遍历
**/
async function getTree(query, loop=true) {
const tree = await Category.find(query);
if ( loop === false )
return tree;
tree.map( async (item) => {
let children = await Category.find({ status: true, pid: mongoose.Types.ObjectId(item._id) });
item.children = children;
// Object.assign(item, {children});
console.dir(item);
} );
return tree;
} );
结果发现返回的 tree 对象数组中的对象没有 children 属性?试了 Object.assign 一样无效, 但在 map 方法里 console.dir(item)又能看到 children 属性?
或者你们遇到这种无限级分类是怎么输出栏目树的?
把 map 换成 for 循环试试,好像 map 里的异步函数会有问题
#1 说的是对的,要改成 for,map 这种是回调函数,async 没用。另外你可以去了解一下 populate,看你的需求大概能一次查询出来。
兄弟 撞头了
map 不能这么用,非得这样用的话,先 map 出一个 promise 数组,再 Promise.all 调用出结果
感谢,已解决。由于分类层级较多,并且有重名的,populate 似乎不太好操作
不懂什么意思。
我们头像一样^^,所以说撞头了 哈哈
async await 真牛逼。。
bash<br>async function getTree(query, loop=true) {<br> const tree = await Category.find(query);<br> if ( loop === false )<br> return tree;<br><br> tree = tree.map( async (item) => {<br> //转成 object<br> item = item.toObject();<br> <br> let children = await Category.find({ status: true, pid: mongoose.Types.ObjectId(item._id) });<br> item.children = children;<br> console.dir(item);<br> <br> return item;<br> } );<br> return tree;<br>} );<br>
手动狗头
map 内部是不支持异步的,推荐了解下 for await of ;或者先得到一个 promise 数组,再使用 Promise.all()
要再包一层 Promise.all
tree = await Promise.all(tree.map(async item=>{
```````````````````
}))
在Node.js中使用Mongoose进行数据库查询时,常见的操作包括查找(find)、查找一个(findOne)、查找ById(findById)等。以下是一些基本查询示例,希望能够帮助你解决查询问题。
1. 引入Mongoose并连接数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourDatabase', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
2. 定义Schema和Model
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
age: Number,
email: String
});
const User = mongoose.model('User', userSchema);
3. 基本查询操作
查找所有用户
User.find({}, (err, users) => {
if (err) console.log(err);
console.log(users);
});
查找一个用户(根据条件)
User.findOne({ name: 'John Doe' }, (err, user) => {
if (err) console.log(err);
console.log(user);
});
根据ID查找用户
User.findById('60d1021602587a4f20578f64', (err, user) => {
if (err) console.log(err);
console.log(user);
});
这些是一些基本的查询操作,根据你的需求可以进一步扩展查询条件、排序、分页等功能。如果有更具体的问题或错误,欢迎提供更详细的描述。