Node.js 是否可以在post方法中更新mongodb集合(使用Mongoose)?
我需要做两件事: 1) 创建50多个集合并用文档填充它们 2) 根据我添加的每个文档中的信息,编辑现有集合 第一个主要用法是第一步,它可以很好地工作。因为我正在向数据库添加集合,所以使用了post方法。现在我需要更新另一个集合,在这种情况下,put甚至补丁http方法将更适合 正确的方法是什么?目前我正在使用model.findOne和mode.Update,但没有更新任何内容。我想知道这是否是因为它是post方法而不是put方法 代码: 在添加有效的令牌后,我调用函数Node.js 是否可以在post方法中更新mongodb集合(使用Mongoose)?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我需要做两件事: 1) 创建50多个集合并用文档填充它们 2) 根据我添加的每个文档中的信息,编辑现有集合 第一个主要用法是第一步,它可以很好地工作。因为我正在向数据库添加集合,所以使用了post方法。现在我需要更新另一个集合,在这种情况下,put甚至补丁http方法将更适合 正确的方法是什么?目前我正在使用model.findOne和mode.Update,但没有更新任何内容。我想知道这是否是因为它是post方法而不是put方法 代码: 在添加有效的令牌后,我调用函数
// This adding works fine
new tokenModel(tokenSchema).save();
// This function is handling the update in a different collection
addTraitsToGame(tokenData);
其功能是:
const addTraitsToGame = (tokenData) => {
// Game is another collection I want to update
Game.findOne({ "opensea.game.address": tokenData.asset_contract.address })
.then(existingGame => {
if (existingGame) {
newArrayToReplaceExistingOne= [];
try {
// Not really relevant, this is how I fill a new object that will be pushed to the new array
for (let i = 0; i < someLength; i++) {
let tokenTrait = tokenData.traits[i];
let gameTrait = existingGame.opensea.traits.find(trait => trait.type === tokenTrait.trait_type);
if (gameTrait && gameTrait.form === "values") {
gameTrait.attributes[tokenTrait['trait_type']] = tokenTrait['trait_count']
// This is the relevant line, filling up the array with objects
newArrayToReplaceExistingOne.push(gameTrait);
}
}
// Updating here!
Game.update(
{ "opensea.game.address": tokenData.asset_contract.address },
{
$set: {
"opensea.game.traits": traitsWithCount
}
},
function (err, user) {
if (err) return handleError(err);
else {
console.log("Update should have been successful");
}
}
);
}
catch (err) {
console.log(err);
}
}
});
const addTraitsToGame=(令牌数据)=>{
//游戏是我想更新的另一个收藏
Game.findOne({“opensea.Game.address”:tokenData.asset_contract.address})
.然后(现有游戏=>{
如果(现有游戏){
newArrayToReplaceExistingOne=[];
试一试{
//不太相关,这是我填充新对象的方式,该对象将被推送到新数组中
for(设i=0;itrait.type===tokenTrait.trait\u-type);
if(gameTrait&&gameTrait.form==“值”){
gameTrait.attributes[tokenTrait['trait\u type']=tokenTrait['trait\u count']
//这是相关行,用对象填充数组
newArrayToReplaceExistingOne.push(游戏特征);
}
}
//更新这里!
Game.update(
{“opensea.game.address”:tokenData.asset_contract.address},
{
$set:{
“opensea.游戏.特征”:traitsWithCount
}
},
函数(错误,用户){
if(err)返回handleError(err);
否则{
log(“更新应该已经成功”);
}
}
);
}
捕捉(错误){
控制台日志(err);
}
}
});
}
之后不会更新任何内容。您也可以使用
model.findOneAndUpdate({_id:req.body.id},{key you need to update:"updated value"},(req,res)=>{
your code here.
}
希望能有所帮助。请发布猫鼬更新代码http PUT或post不会改变猫鼬的行为。您的model.update或model.findOne可能存在问题。请输入一些有问题的代码以确定问题。使用相关代码编辑