简体   繁体   English

用猫鼬在对象数组中存储对象

[英]Storing objects in object array with Mongoose

I am trying to push several comment objects into my UserSchema in mongoose. 我试图用猫鼬将几个注释对象推入我的UserSchema中。 However, whenever I run this code, it only creates the "_id" fields for each comment entry, ie 但是,每当我运行此代码时,它只会为每个注释条目创建“ _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. 当然,我具有更多的属性,但是我仅包含了一个代码片段,以表明即使是一个小示例也不起作用。

There was an extra "comments" in the call because of how I declared the CommentSchema. 由于我声明CommentSchema的方式,因此通话中有一个额外的“注释”。 Painfully obvious now! 现在很痛苦!

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

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