gpt4 book ai didi

node.js - 获取集合中的所有项目

转载 作者:太空宇宙 更新时间:2023-11-04 00:33:50 25 4
gpt4 key购买 nike

我正在尝试使用一些默认的虚拟数据填充数据库,以加快测试速度。这是使用 https://github.com/angular-fullstack/generator-angular-fullstack 的项目的一部分我第一次尝试使用 promise 。

假设我有类似的东西:

Thing.create({
name: 'thing 1'
}, {
name: 'thing 2'
}).then((things) => {
console.log(things);
});

为什么控制台日志只输出thing 1而不是整个集合?

根据 Mongoose 文档 http://mongoosejs.com/docs/api.html#model_Model.create ,该方法返回一个 promise ,这似乎对我没有帮助。

最佳答案

为了让 Mongoose 返回 Promise,您需要在 Mongoose 实例中进行相应的设置:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

此外,如果您想一次创建多个文档,您应该将一个数组传递给.create方法:

let things = [
{
"name": "Thing 1"
},
{
"name": "Thing 2"
},
{
"name": "Thing 3"
}
];

Thing.create(things).then(newThings => {
console.log(newThings);
});

// Outputs
[ { name: 'Thing 1', _id: 57fd82973b4a85be9da73b25 },
{ name: 'Thing 2', _id: 57fd82973b4a85be9da73b26 },
{ name: 'Thing 3', _id: 57fd82973b4a85be9da73b27 } ]

关于node.js - 获取集合中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39988601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com