javascript - ".findOneAndUpdate()"未正确更新数据库(Mongodb 和 Node.js)

标签 javascript node.js mongodb mongodb-query nosql

我尝试使用 .findOneAndUpdate() 更新我的数据库。

没有错误消息,但是这部分数据库没有用新数据更新。嵌入文档 competitorAnalysisTextData 仍然是空的。

// on routes that end in /users/competitorAnalysisTextData
// ----------------------------------------------------
router.route('/users/competitorAnalysisTextData/:userName')

// update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisTextData)
.post(function(req, res) {

    console.log('1');

// Just give instruction to mongodb to find document, change it;
// then finally after mongodb is done, return the result/error as callback.
User.findOneAndUpdate(
    { userName : req.params.userName},
    {
        $set:
        {   "competitorAnalysis.firstObservation" : req.body.firstObservation,
            "competitorAnalysis.secondObservation" : req.body.secondObservation,
            "competitorAnalysis.thirdObservation" : req.body.thirdObservation,
            "competitorAnalysis.brandName" : req.body.brandName,
            "competitorAnalysis.productCategory" : req.body.productCategory
        }
    },
    { upsert: true },
    function(err, user) {
        // after mongodb is done updating, you are receiving the updated file as callback
        console.log('2');
        // now you can send the error or updated file to client
        if (err)
            return res.send(err);

        return res.json({ message: 'User updated!' });
    });

})

更新

这是我的“用户”架构部分:

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Require the crypto module for password hash
'use strict';
var crypto = require('crypto');

// create competitorAnalysisSchema
var CompetitorAnalysis = new Schema({
    firstObservation: { type: String },
    secondObservation: { type: String },
    thirdObservation: { type: String },
    brandName: { type: String },
    productCategory: { type: String }
});
// create competitorAnalysisPhotoSchema
var CompetitorAnalysisPhoto = new Schema({
    photo1: {type: String},
    photo2: {type: String},
    photo3: {type: String},
    photo4: {type: String}
});
// create UserSchema
var UserSchema = new Schema({
    userName: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    currentDemo: { type: String },
    nextDemo: { type: String },
    startTime: { type: String },
    startLocation: { type: String },
    arriveTime: { type: String },
    arriveLocation: { type: String },
    leaveTime: { type: String },
    leaveLocation: { type: String },
    competitorAnalysis: [CompetitorAnalysis],
    competitorAnalysisPhoto: [CompetitorAnalysisPhoto],
    created_at: Date,
    updated_at: Date
});

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', UserSchema);

// make this available to our users in our Node applications
module.exports = User;

最佳答案

在 JavaScript 中,如果你想更新数组中的对象,你需要选择索引

var arr = [{name: "person1"},{name:"person2"}]
arr[0].name = "myname"
arr[1].name = "myFriend"
<小时/>

所以在mongodb中也是一样的,查看这个link有关详细示例,或者您可以手动输入索引,以进行快速破解。

User.findOneAndUpdate(
  { userName : req.params.userName},
  {
    $set:
    {   "competitorAnalysis.0.firstObservation" : req.body.firstObservation,
        "competitorAnalysis.0.secondObservation" : req.body.secondObservation,
        "competitorAnalysis.0.thirdObservation" : req.body.thirdObservation,
        "competitorAnalysis.0.brandName" : req.body.brandName,
        "competitorAnalysis.0.productCategory" : req.body.productCategory
    }
  },
  { upsert: true },
  function(err, user) {
    // after mongodb is done updating, you are receiving the updated file as callback
    console.log('2');
    // now you can send the error or updated file to client
    if (err)
        return res.send(err);

    return res.json({ message: 'User updated!' });
  });

})
<小时/>

您应该使用上面的代码来更新嵌套数组而不是添加到空数组。 在 javascript 中,如果数组仍然,我们使用 .push() 来添加,而在 mongodb 中命令是 $push

var arr = []
arr.push({name:"person1"})

关于javascript - ".findOneAndUpdate()"未正确更新数据库(Mongodb 和 Node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301525/

相关文章:

node.js - MongoDB 不使用 NodeJS 驱动程序应用程序返回数据

javascript - 使用脚本读取文件

node.js - 在 docker 容器内重新加载代码。颗粒物。 Node js

javascript - Passport 回调500服务器错误

node.js - Mongodb如何在Find Promise中插入?

mongodb - 按组保留最近的 N 条记录,同时删除其他记录

javascript - Node-express 中的多数据库动态切换

javascript - 尝试匹配两个数组中的值,并且仅在部分值完全匹配时才删除

javascript - 有没有不会弄乱代码的所见即所得的 HTML 编辑器?

node.js - Mongo递增ID问题