[英]Using mongoose to write and retrieve data in nodejs backend
im newer about MongoDb and Node.Js.我更新了 MongoDb 和 Node.Js。
I should check if an Asset exists, and then (if not exist) create it.我应该检查资产是否存在,然后(如果不存在)创建它。
This is the Asset schema这是资产模式
var Schema = mongoose.Schema;
var AssetSchema = new Schema({
name: String,
creationDate: { type: Date, default: Date.now },
}, {collection: 'Assets'})
var Asset = mongoose.model('Asset', AssetSchema)
Check if asset exists检查资产是否存在
async function assetExists(assetName, callback) {
if(assetName){
Asset.findOne({name: assetName}
, function(err, asset){
if(err){
callback(err, null);
console.log('Error on find asset '+assetName)
} else {
callback(null, asset.name); //Using this I get the asset.name or undefined
}
});
}
}
Create new one新建一个
async function addAsset(assetName, callback){
if(assetName){
var newAsset = new Asset({name: assetName})
await newAsset.save( function(err, asset){
if(err){
callback(err, null);
console.log('Error on add asset '+assetName)
}
})
}
}
Anyway I checked, and no one of these two methods seem to work.不管怎样,我查了一下,这两种方法似乎都行不通。 I thought it was a connection problem, but the connection works.
我以为这是一个连接问题,但连接有效。
I use MongoDB Cloud, this is the connection string我使用 MongoDB Cloud,这是连接字符串
mongodb+srv://<username>:<password>@<clustername>.4ny68c7.mongodb.net/?retryWrites=true&w=majority
What am i missing?我错过了什么? Do both method are correct?
两种方法都正确吗? Thanks
谢谢
The problem with your methods are you're making them async
but using them in a synchronous way.您的方法的问题是您使它们
async
但以同步方式使用它们。
Refactored:重构:
async function assetExists(assetName) {
const asset = await Asset.findOne({name: assetName});
return asset ? asset : false; // returns asset if exists otherwise false;
}
While creating a new Asset you can check if an Asset with given name exists or not:创建新资产时,您可以检查是否存在具有给定名称的资产:
async function addAsset(assetName) {
try {
const isAssetExisting = await assetExists(assetName); // re-using the above function
if (!isAssetExisting) {
const newAsset = new Asset({ name: assetName });
return await newAsset.save() // returns newly created asset
}
return isAssetExisting; // otherwise returns existing asset
} catch (err) {
// Your way of handling error
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.