【问题标题】:Why is my mongoose document property not properly setting to another _id property为什么我的猫鼬文档属性没有正确设置为另一个 _id 属性
【发布时间】:2015-03-17 23:27:35
【问题描述】:

我正在尝试设置一个简单的猫鼬测试文件,并且得到了一些非常令人困惑的结果。当我运行以下代码时:

var mongoose = require('mongoose');
var Schema = mongoose.Schema; 
mongoose.connect('mongodb://localhost/myapp');

var personSchema = Schema({
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
  creator : { type: Schema.Types.ObjectId, ref: 'Person' },
  title    : String,
  fans     : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

var aaron = new Person({name: 'Aaron', age: 100 });

aaron.save(function (err) {
  if (err) console.log("something didnt work!");

  var story1 = new Story({
    title: "Once upon a timex.",
    creator: aaron._id  // assign the _id from the person to creator
  });
  console.log(aaron._id);
  story1.save();
});
Story.findOne({ title: 'Once upon a timex.' },function(err,story){
  console.log(story); // printing here
});

我得到这个输出:

{
  _id: 54b9e08ed983b41d432473e4,
  title: 'Once upon a timex.',
  _creator: 0,
  __v: 0,
  fans: [] 
}
54bcacb4c812ec812382b6b2

这里面有很多没有真正意义的东西。从我的代码中可以看出,我只有 console.log();两件事:

  • arron._id
  • 在 aaron 的保存回调中创建的故事文档

问题 1: 当我们打印出故事对象时,我们看到 creator 字段设置为 0(我们稍后会谈到),并且由于某种原因添加了下划线(我假设是因为它链接到 ObjectId)。我还尝试向创建者添加下划线,就像它在文档中显示的那样,这导致创建者属性根本无法保存到文档中。谁能解释 _ 如何与猫鼬互动?

问题 2: 当我们尝试将 creator:aaron_id 设置为 0 时,我们知道 arron._id 不是 0,因为我们在同一范围内成功打印了它。我做错了什么?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    问题 1:问题在于 find 查询在保存查询之前执行(请记住它们是异步执行的)。

    试试:

    var aaron = new Person({name: 'Aaron', age: 100 });
    
    aaron.save(function (err) {
      if (err) console.log("something didnt work!");
    
      var story1 = new Story({
        title: "Once upon a timex.",
        creator: aaron._id  // assign the _id from the person to creator
      });
      console.log(aaron._id);
      story1.save(function(err){
        Story.findOne({ title: 'Once upon a timex.' },function(err,story){
           console.log(story); // printing here
        });
      });
    });
    

    问题 2:您确定您没有查找您尝试保存的旧对象吗?我有一种感觉,在某些时候,故事有属性 _creator,而您将其更改为“创建者”,但它会找到您的旧文档,因为您没有按 id 查询。尝试将您的故事查询更改为:

    Story.findOne({ title: 'Once upon a timex.', creator: aaron._id },function(err,story){
      console.log(story); // printing here
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多