Javascript 使用对象[node.js]创建或更新mongodb

Javascript 使用对象[node.js]创建或更新mongodb,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我正在尝试创建/更新mongodb 为什么这个代码总是出错 我的数据库模式: var userSchema = new Schema({ userAddress: {street: {type: String}, city: {type: String}, zip: {type: String}}, userId: { type: String, required: true, unique: true }, }); var AddressObj = { street:address

我正在尝试创建/更新mongodb

为什么这个代码总是出错

我的数据库模式:

var userSchema = new Schema({
  userAddress: {street: {type: String}, city: {type: String}, zip: {type: String}},
  userId: { type: String, required: true, unique: true },

});

var AddressObj = { street:address['addressLine1'], city:address['city'], zip:address['postalCode']  };


User.findOneAndUpdate(
        {userId:  userID}, 
        { $set: { "userAddress" : AddressObj} },
        function(err, doc){
            if(err){
                console.log("Something wrong when updating data!");
            }

            console.log(doc);
        });

没有错误。数据库中没有任何项目

如果不存在新文档,您需要告诉mongoose创建新文档。可以通过将upsert选项指定为第三个参数的一部分来完成此操作。像这样:

User.findOneAndUpdate(
        {userId:  userID}, 
        { $set: { "userAddress" : AddressObj} },
        {upsert:true, new:true},  //upsert to create a new doc if none exists and new to return the new, updated document instead of the old one. 
        function(err, doc){
            if(err){
                console.log("Something wrong when updating data!");
            }

            console.log(doc);
        });

你的错误是什么?name的模式类型是什么?是String还是schema.Types.Mixed?你能在这里发布你的用户模式吗?请发布模式更新我的代码。我将非常感谢您的帮助。真奇怪。我一点错误也没有。Just nodejs不保存我的条目:如果要创建一个条目,为什么要使用find one和update?在我看来,它不创造一个是正常的,因为它没有在手之前找到一个。