简体   繁体   English

猫鼬使用save()方法不会保存文档

[英]document wont save using save() method with mongoose

I have this schema: 我有这个架构:

var UserSchema = mongoose.Schema({
    analytic: {
      type: Object, 
      default: {
        today:[],
        weekly:[],
        monthly:[],
        yearly:[],
        allTime:[]
      }
    }
});

let User = mongoose.model("bloger", UserSchema);
module.exports = {User};

and I am trying to save some data into one of the arrays like so: 我正在尝试将一些数据保存到数组之一中,如下所示:

    User.findOne({username:username}, (e, user) => {
        if (e) {
            res.send('error fetching post')
        }
        else if (!user) {
            res.send('no user found')
        }
        else if (user) {
            user.analytic.today.push(req.body.visitor) // push the data object to the array
            user.save((e, doc) => {
                if (e) {
                    res.send(e)
                } 
                if (doc) {
                     console.log('user saved')
                    res.send(doc)
                }
            })
        }
    })
}) 

I am getting the doc object on save() and not the e so I though it should have save it but it wasn't. 我在save()而不是e上获得了doc对象,所以我虽然应该保存它,但事实并非如此。

I have had a similar issue before this is because I am not defining a new Model I am just passing a JSON object. 在此之前,我曾遇到过类似的问题,因为我没有定义新模型,而只是传递了JSON对象。

Instead of saving the object you need to create a new model and save that. 无需保存对象,您需要创建一个新模型并将其保存。

Try creating a new model passing the save into it like below; 尝试创建一个新模型,将保存内容传递给它,如下所示;

var newUser = new User(user);
newUser.save((e, doc) {
    if (e) {
       res.send(e)
    } 
    if (doc) {
        console.log('user saved')
        res.send(doc)
    }
});

Making sure you require the User Model inside the script. 确保在脚本中需要用户模型。

Performing deep modifications in objects not in your schema makes Mongoose oblivious to those changes, preventing it from knowing what to save (and from making efficient atomic updates). 对不在您架构中的对象执行深层修改会使Mongoose忽略这些更改,从而使其无法知道要保存的内容(以及进行有效的原子更新)。 The end result is that, when calling .save , Mongoose thinks there's nothing modified and therefore does nothing. 最终结果是,当调用.save ,Mongoose认为没有任何修改,因此什么也不做。

In your particular scenario, you have two options: 在您的特定情况下,您有两个选择:

1. Add your analytics sub-arrays to your schema 1.将analytics子数组添加到架构

This is the best option and allows for finer control of everything: 这是最好的选择,可以对所有内容进行更好的控制:

const UserSchema mongoose.Schema({
  analytic: {
    today: [{}],
    weekly: [{}],
    monthly: [{}],
    yearly: [{}],
    allTime: [{}],
  }
});

With this, those arrays are now known to Mongoose and everything should work correctly. 这样,Mongoose现在就知道了这些数组,并且一切都应该正常工作。

Note that you don't need defaults in this case, as Mongoose is smart enough to create the arrays as needed. 请注意,在这种情况下,您不需要默认值,因为Mongoose足够聪明,可以根据需要创建阵列。

2. Manually mark modified object as modified 2.手动将修改的对象标记为已修改

If for any reason you don't want or can't modify the schema, you can manually mark the analytic object as modifies so Mongoose knows of it: 如果出于某种原因您不希望或无法修改架构,则可以手动将analytic对象标记为已修改,以便Mongoose知道:

user.analytic.today.push(req.body.visitor) // push the data object to the array
user.markModified('analytic'); // mark field as modified
user.save(...);

This signals Mongoose that analytic or any of its children have changed and triggers an update when calling .save . 这表示Mongoose analytic或它的任何子级已更改,并在调用.save时触发更新。 Note however that Mongoose views this as a full change in the object, while with option 1 it can use $push instead. 但是请注意,Mongoose将此视为对象的完整更改,而对于选项1,它可以使用$push代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM