我正在尝试抽象一个教程,让MEAN stack使用MongoAtlas而不是本地实例。我的Mongoose连接到Atlas DB工作正常(只要我可以连接到DB)。但是我不能执行save()。我相信这与我创建connection对象的方式有关,但我似乎不能指出问题所在。
我假设通过添加bufferCommands = false,这将告诉我它不工作的原因是我错误地打开了connection对象,但我没有看到任何错误-只是挂起了。
product.js
var mongoose = require('mongoose');
var db = mongoose.connection;
var Schema = mongoose.Schema;
var schema = new Schema ({
imagePath: {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required:true}
});
var connection = mongoose.createConnection('mongodb+srv://<user>:<password>@cluster0-dpwmr.gcp.mongodb.net/Shopping?retryWrites=true', {useNewUrlParser:true})
module.exports = connection.model('Product', schema);product-seeder.js
var Product = require('../models/product');
var mongoose = require('mongoose');
//mongoose.set('bufferCommands', false);
var products =[
new Product({
imagePath:'https://picsum.photos/250/?random',
title: 'Item 1',
description: 'This is a thing',
price: 10
}),
new Product({
imagePath:'https://picsum.photos/251/?random',
title: 'Item 2',
description: 'This is another thing',
price: 14
}),
new Product({
imagePath:'https://picsum.photos/253/?random',
title: 'Item 3',
description: 'This is a slightly longer description',
price: 30
})
];
var done = 0;
for (i=0; i++; i<products.length){
products[i].save(function(err, res){
if (err){
console.log(err);
exit();
}
done++;
if (done === products.length){
exit();
}
});
}
function exit(){
mongoose.disconnect();
}我希望这会创建一个新的文档'products‘,并在Shopping集合中写入它,但这并没有发生,只是很多东西都没有。
发布于 2019-03-27 09:10:31
我使用以下几种方法来解决这个问题:
使用mongoose.connect()
var mongoose = require('mongoose');
var db = mongoose.connection;
var Schema = mongoose.Schema;
var schema = new Schema ({
imagePath: {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required:true}
});
mongoose.connect('mongodb+srv://<UserName>:<Password>@cluster0-dpwmr.gcp.mongodb.net/', {dbName:'Shopping', useNewUrlParser:true})
.then( () => {
console.log('Connection to the Atlas Cluster is successful!')
})
.catch( (err) => console.error(err));
const conn = mongoose.connection;
module.exports = mongoose.model('Product', schema);var Product = require('../models/product');
var mongoose = require('mongoose');
var products =[
new Product({
imagePath:'https://picsum.photos/250/?random',
title: 'Item 1',
description: 'This is a thing',
price: 10
}),
new Product({
imagePath:'https://picsum.photos/251/?random',
title: 'Item 2',
description: 'This is another thing',
price: 14
}),
new Product({
imagePath:'https://picsum.photos/253/?random',
title: 'Item 3',
description: 'This is a slightly longer description',
price: 30
})
];
const conn = mongoose.connection;
processArray(products);
async function processArray (array) {
for (const item of products){
console.log (item)
await item.save();
}
conn.close();
}https://stackoverflow.com/questions/55329856
复制相似问题