[英]How to make save first and find below with mongoose
我是nodejs和貓鼬的初學者。
所以我有這樣的麻煩:
之后,創建架構,模型並將數據放入其中並保存,我想再次查找。
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var typePlantSchema = new Schema({
namePlant:String,
estimateDuration:Number,
conditionPh:Number
});
var typePlantModels= mongoose.model('typePlant',typePlantSchema);
var typePlantModel = new typePlantModels();
mongoose.connect('mongodb://localhost/AeroDB', function (err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
typePlantModel.namePlant='tam';
typePlantModel.estimateDuration=10;
typePlantModel.conditionPh=7;
typePlantModel.save();
typePlantModels.find({namePlant:"tam"},function(err,docs){
if(err){
console.log(err);
}
else {console.log(docs);}
});
但是,當我第一次運行代碼時,我找不到任何結果。 如果再運行一次,我發現1個結果(事件2個結果)。 這意味着查找功能超出了保存功能。 我認為這取決於回調函數的順序。 那么,您有什么解決方案可以使其正常工作嗎? 當然,不要將查找功能放在保存功能中。 請幫我做。
更新更多問題
實際上,我想將其傳輸到databse API。 看起來像這樣:
var typePlantModels= mongoose.model('typePlant',typePlantSchema);
var typePlantModel = new typePlantModels();
typePlant.prototype=typePlantModel;
typePlant.prototype.findByName=function(name){
self=this;
typePlantModels.find({namePlant:self.namePlant},function(err,docs){
console.log(docs)}
}
module.exports=typePlant;
我可以將其放在保存功能上或使用save()。 請幫助我使它工作。 非常感謝
在save()
完成之前,您的find()
函數正在運行。
解決方案是使用save()
的回調函數。
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var typePlantSchema = new Schema({
namePlant:String,
estimateDuration:Number,
conditionPh:Number
});
var typePlantModels= mongoose.model('typePlant',typePlantSchema);
var typePlantModel = new typePlantModels();
mongoose.connect('mongodb://localhost/AeroDB', function (err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
typePlantModel.namePlant='tam';
typePlantModel.estimateDuration=10;
typePlantModel.conditionPh=7;
typePlantModel.save().then(function(){
typePlantModels.find({namePlant:"tam"},function(err,docs){
if(err){
console.log(err);
}
else {console.log(docs);}
});
});
更新1:
要使函數成為外部函數,請在外部聲明函數,而不是在回調中使匿名函數:
typePlantModel.save().then(findThis("something"));
function findThis(val){
typePlantModels.find({namePlant:val},function(err,docs){
if(err){
console.log(err);
}
else {console.log(docs);}
});
}
現在,您可以隨時使用findThis()
。
由於節點是異步的,因此您將需要在保存的回調中使用find
。 像這樣:
typePlantModel.save(function(){
typePlantModels.find({namePlant:"tam"},function(err,docs){
if(err){
console.log(err);
} else {
console.log(docs);
}
});
為了使這段代碼更清晰,我建議您閱讀Promise
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.