gpt4 book ai didi

node.js - Mongo/Mongoose 检查项目是否存在

转载 作者:可可西里 更新时间:2023-11-01 10:04:10 25 4
gpt4 key购买 nike

我对使用 Mongo 和 Mongoose 构建大型 Web 应用程序还很陌生,我想知道检查项目是否存在的正确方法是什么。

我在下面对函数进行了评论,因此应该很容易理解我在做什么以及我遇到了什么困难。所以基本上我正在创建的是: item_exists ?什么都不做:保存。我目前已经删除了“保存”功能,因为我不太确定它应该放在哪里。

app.post('/tracks/add/new', function (req, res) {

var newTrack;

// loop through the objects in req.body
// item_exists ? do nothing : save

for (var i = 0; i < req.body.length; i++) {

newTrack = new tracksTable({
for_user: req.user._id,
title: req.body[i].title,
artist: req.body[i].artist,
artwork: req.body[i].artwork,
source: req.body[i].source,
stream: req.body[i].stream
});

// check if the item already exists by
// first finding the 'for_user' field and
// any tracks associated with it (title)

var query = tracksTable.find({});

query
.where('for_user', req.user._id)
.select('title')
.exec(function (err, data) {
for (var x = 0; x < data.length; x++) {

// this is where I've hit a wall...
// does 'this' track in the database match
// one in the request?

}
});

}

});

最佳答案

如果您正在寻找 tracksTable 集合中的一项,您可以这样做:

tracksTable.findOne({for_user: req.user._id}, function(err, tracksTableItem) {
if (err) {
console.log("MongoDB Error: " + err);
return false; // or callback
}
if (!tracksTableItem) {
console.log("No item found, creating tracksTable item");

tracksTable.create(
{
for_user: req.user._id,
title: req.body[i].title,
artist: req.body[i].artist,
artwork: req.body[i].artwork,
source: req.body[i].source,
stream: req.body[i].stream
}, function(err, createdItem) {
if (err) {
console.log("MongoDB Error: " + err);
return null; // or callback
}
}
);
}
else {
console.log("Found one tracksTable item: " + tracksTableItem.for_user);
// here you could even update your existing item using "tracksTable.save"
}
return true; // or callback
}

关于node.js - Mongo/Mongoose 检查项目是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232423/

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