“.findOneAndUpdate()”没有正确更新数据库(Mongodb& Node.js)

时间:2016-09-02 22:38:52

标签: 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;

1 个答案:

答案 0 :(得分:1)

在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"})