2015-11-14 18 views
0

,當我在使用MongoDB中,我得到錯誤對象#有沒有方法「限制」運行的NodeJS代碼對象#<Promise>有沒有方法「限制」

var collection = db.get('categories'); 
console.log(collection.find().limit(1).sort({ _id : -1 })); 

。我到節點一個初學者,很堅持節點

本節這裏是歌廳最後插入文檔完整的代碼。

router.post('/addcategory', function(req, res) { 

// Set our internal DB variable 
var db = req.db; 

// Get our form values. These rely on the "name" attributes 
var name = req.body.name; 
var description = req.body.description; 




// Set our collection 
var collection = db.get('categories'); 

// Submit to the DB 
collection.insert({ 

    "name" : name, 
    "description" : description, 


}, function (err, doc) { 
    if (err) { 
     // If it failed, return error 
     res.send("There was a problem adding the information to the database."); 
    } 
    else { 
     // And forward to success page 
     /******************/ 
     console.log(collection.find().limit(1).sort({ _id : -1 })); 


     /*************/ 
    } 
}); 
}); 
+0

什麼版本的驅動程序的MongoDB您使用的是?如果將'var collection = db.get('categories');'更改爲'var collection = db.collection('categories');'? – JoGoFo

+1

您使用mongodb的模塊是什麼? – mscdex

+0

@JoGoFo當我這樣做,我得到這個錯誤'對象#有沒有方法「收集」' – Mohammed

回答

0

在這裏失去了信息的關鍵部分是,你使用的僧侶,而不是本地的MongoDB Node.JS驅動程序。您對find()的命令是如何使用本地驅動程序(使用上面的@BlakesSeven建議的異步進行異步處理),但Monk的工作方式稍有不同。

試試這個:

collection.find({}, { limit : 1, sort : { _id : -1 } }, function (err,res) { 
    console.log(res); 
}); 
0

的方法仍然是異步的,所以你仍然需要調用ITM無論是作爲與.then()或回調的承諾。沒有方法是同步的,並返回結果內聯。

而且從驅動程序返回的結果爲s「光標」,而不是你所期望的對象(S)。你要麼迭代返回的遊標或者只是使用.toArray()或類似的轉換:

collection.find().limit(1).sort({ "_id": -1 }).toArray().then(function(docs) { 
    console.log(docs[0]); 
}); 

或者:

collection.find().limit(1).sort({ "_id": -1 }).toArray(function(err,docs) { 
    console.log(docs[0]); 
}); 

但實際上整個前提是不正確的。你似乎基本上想要返回剛剛插入的內容。在您的代碼中有更正的事件,返回的文檔不一定是您剛纔插入的文檔,而是插入到集合中的最後一個文檔,可能是通過其他操作發生的,也可能是從另一個源調用此路由。

如果你願意,你插什麼時候回來再而調用.insertOne()方法,檢查結果:

collection.insertOne({ "name": name, "description": description },function(err,result) { 
    if (err) { 
    res.send("There was an error"); 
    } else { 
    console.log(result.ops) 
    } 
}); 

.insert()方法被認爲是過時了,但基本上返回同樣的事情。代價是,他們返回insertWriteOpResult對象,其中ops屬性包含插入到文檔(S)和他們的_id值(S),

+0

我收到此錯誤'類型錯誤:對象#有,當我把你的代碼沒有方法「limit''。我不知道我在哪裏錯了。 – Mohammed

+0

@Mohammed是的,這是你的問題,這是什麼答案。你試圖在代碼中返回的對象不是「結果」,而是「Promise對象」,因此是錯誤。這顯示了你如何通過改變你的代碼來得到那個對象的結果。它還解決了您似乎希望返回的對象是您剛剛插入的對象。它不可能是你的代碼,以及確保列出的替代方法。 –

相關問題