使用Mongoose在Object对象数组中存储对象

时间:2020-12-31 20:21:16

I am trying to push several comment objects into my UserSchema in mongoose. However, whenever I run this code, it only creates the "_id" fields for each comment entry, i.e. 使用Mongoose在Object对象数组中存储对象

我试图在mongoose中将几个评论对象推送到我的UserSchema中。但是,每当我运行此代码时,它只为每个注释条目创建“_id”字段,即

function saveUser(user) {
  user.save(function (err) {
    if (err)
      console.log(err);
  });
}

function createUser(req, res, callback) {
    var userData = new User({username: req.params.username});

    getUserComment(req, res, function(testComment) {
        userData.comments.push({body: testComment});
        saveUser(userData);
    });
}

My schemas:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CommentSchema = new Schema({
    comments: {
            score: Number,
            body: String
            }
});

var UserSchema = new Schema({
    username: {type: String, unique: true},
    comments: [CommentSchema]
}, { collection: 'user'});

module.exports = mongoose.model('User', UserSchema);

Of course, I have more properties but I just included a snippet to show that even one small example does not work.

当然,我有更多的属性,但我只是包含一个片段,以显示即使一个小例子也不起作用。

1 个解决方案

#1


0  

There was an extra "comments" in the call because of how I declared the CommentSchema. Painfully obvious now!

由于我如何声明CommentSchema,因此调用中有一个额外的“注释”。现在非常明显!

#1


0  

There was an extra "comments" in the call because of how I declared the CommentSchema. Painfully obvious now!

由于我如何声明CommentSchema,因此调用中有一个额外的“注释”。现在非常明显!